我对一个简单的Angular组件有疑问。我使用反应式表单插入选项,然后按*ngFor
循环查看结果。
true
我想看到图标fa-check
。 false
我只想看not
。我正在尝试使用对象循环数组,但是*ngFor
不起作用。这是代码,这是stackblitz-project
模板
<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
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();
}
}
答案 0 :(得分:0)
更新模板中的选项值:
<option *ngFor="let option of optionArray" [value]="option.option">
{{option.label}}
</option>
在addOption方法中更新密钥名称:
let option = {
label: this.selectOptionForm.value.yesOrNot,
};