【问题标题】:*ngFor not display*ngFor 不显示
【发布时间】:2018-04-30 11:03:02
【问题描述】:

嘿,我知道这个问题经常出现,但正常的修复方法不起作用。

这是我的代码

export class CourseReviewFormComponent implements OnInit { 
 form: FormGroup
 questionnaire: string[] = [];
 currentQuestionsValue: string[] = [];

 constructor(private serverData: ServerService) { }
  ngOnInit() {
    this.onGetForm();   
   }

 onGetForm() {
   this.serverData.getData('questionnaire/Student Course Review')
     .subscribe(
        (response: Response) => {
         this.questionnaire = response.json();
         let key = Object.keys(this.questionnaire);
         for (let i = 0; i < key.length; i++) {
           this.currentQuestionsValue.push(this.questionnaire[key[i]].items)
         }
         console.log('current Questions Value', this.currentQuestionsValue);
         },
          (error) => console.log('Form Error', error)
         )
      }
    }

我的模板

 <form>
  <div *ngFor="let data of currentQuestionsValue">
    <strong> {{ data.sno }}). </strong>
    <span>{{ data.question}}</span>
    <div>
      <label *ngFor="let op of data.options; let i = index">
        <input type="radio" name="option" [value]="i">
        <span>{{ op }}</span>
      </label>
    </div>
  </div>
</form>

但是 ngFor 不显示任何数据:

console.log('current Value', this.currentValue); 中效果很好。

但是,当我在 DOM 中运行 ngFor 循环时,它不起作用。

【问题讨论】:

  • 查看控制台输出,currentQuestionsValue 是一个只有一个元素的数组(也是一个数组)。那个内部数组很可能就是你要找的那个。
  • 你能告诉我我在 dom 中的显示方式吗
  • 使用this.currentQuestionsValue = this.currentQuestionsValue[0]它会为你解决问题。

标签: angular typescript firebase firebase-realtime-database angular-forms


【解决方案1】:

您需要获取数组的第一项并迭代其值,该值也是一个数组。

ServerService 中,我会添加中间步骤来转换这样的可观察对象:

.map(data => data.json())
.map(json => json[0])

【讨论】:

  • @Adeel,对于这个答案,请查看此 URL 以获取更多信息。 medium.com/@luukgruijs/…
  • @Swanand 提出了一个很好的观点。该文章指定您可以使用异步管道订阅控制器或视图。我是第二个的大力倡导者,但是,我觉得这不是问题的一部分。
  • @Swanand 我试过了,但还是没有解决,你能帮帮我吗?我对 Observables 很困惑。
【解决方案2】:

你在找这个吗?

let data of currentQuestionsValue[0]

【讨论】:

    猜你喜欢
    • 2019-09-18
    • 2017-01-06
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2019-11-11
    • 2020-09-02
    • 2021-06-28
    相关资源
    最近更新 更多