简体   繁体   English

如何解决 ngFor 用于 Angular 渲染的问题

[英]How can I solve a problem with ngFor for Angular rendering

I have a problem with a simple Angular component.我对一个简单的 Angular 组件有疑问。 I'm using a reactive form to insert an option then I loop by *ngFor to see the results.我正在使用响应式表单来插入一个选项,然后通过*ngFor循环查看结果。

  • If true I want to see icon fa-check .如果为true ,我想查看图标fa-check
  • If false I want to see only not .如果是false的,我只想看not

I'm trying to loop an array with objects but the *ngFor does not work.我正在尝试使用对象循环数组,但*ngFor不起作用。 This is the code and this is a stackblitz-project这是代码,这是一个stackblitz项目

Template模板

<form [formGroup]="selectOptionForm">
    <select class="form-control" id="yesOrNot" name="yesOrNot" formControlName="yesOrNot">
      <option *ngFor="let option of optionArray" [value]="option">
          {{option.label}}
      </option>   
    </select>
    <button  type="button"  (click)="addOption()">ADD</button>

</form>

<div
*ngFor="let option of selectOptionArray; let i = index;">
<div> {{ option.label }}</div>
</div>

TypeScript TypeScript

import { Component, VERSION } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

selectOptionForm: FormGroup;
selectOptionArray: any[] = [];

optionArray = [
  {
    label: 'yes',
    option: true
  },
   {
    label: 'not',
    option: false
  },
];

constructor(
    private fb: FormBuilder // form FormBuilder
  ) { }

ngOnInit() {
    // dichiaro il form con i contenuti
    this.selectOptionForm = this.fb.group({ 
      yesOrNot: [null]
    });
  }

 addOption(){
   if (this.selectOptionForm.valid) {
      let option = { 
        yesOrNot: this.selectOptionForm.value.yesOrNot,
      };
      this.selectOptionArray.push(option);
      console.log(option)
    }

    this.selectOptionForm.reset();
 }
}

Update option value in template:更新模板中的选项值:

<option *ngFor="let option of optionArray" [value]="option.option">
    {{option.label}}
</option>   

Update key name in addOption method:更新 addOption 方法中的键名:

let option = { 
    label: this.selectOptionForm.value.yesOrNot,
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM