我想使用角形的反应形式添加动态元素。我正在关注此链接:https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/。
我正在做与该链接完全相似的操作。但是我遇到了错误。 下面是代码:
ts文件:
orderForm: FormGroup;
items: FormArray;
constructor(private formBuilder: FormBuilder ) { }
ngOnInit() {
this.orderForm = this.formBuilder.group({
iems: this.formBuilder.array([ this.createItem() ])
})
}
createItem(): FormGroup {
return this.formBuilder.group({
checked: ''
})
}
addDynamicCheckBox() {
this.items = this.orderForm.get('items') as FormArray;
this.items.push(this.createItem());
}
模板文件:
<div [formGroup]="orderForm">
{{ orderForm.controls.items.controls }}
<div class="row" formArrayName="items" *ngFor="let item of orderForm.get('items').controls; let i=index">
<div class="col-10" [formGroupName]="i">
<mat-checkbox formControlName="checked"></mat-checkbox>
</div>
<div class="col-2" style="float: right">
<button mat-raised-button>Remove</button>
</div>
</div>
</div>
修改
我想设置formArray控件的值。我看不到任何价值。仅显示复选框。我编写的以下代码:
ts文件
setCheckBoxValue() {
this.items = this.orderForm.get('items') as FormArray;
this.data.data.forEach((element) => {
this.items.push(this.formBuilder.group({
checked: true,
selected: element
}))
});
}
html文件
<div [formGroup]="orderForm">
<div class="row" formArrayName="items" *ngFor="let item of orderForm.get('items').controls; let i=index">
<div class="col-8" [formGroupName]="i">
<mat-checkbox formControlName="checked">{{item.checked}}</mat-checkbox>
</div>
</div>
check box value: {{ orderForm.get('items').controls.checked }}
</div>
``
答案 0 :(得分:1)
您的代码 iems -> 项目中似乎有一个错字。请查看更新后的答案
TS文件
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
orderForm: FormGroup;
items: FormArray;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.orderForm = this.formBuilder.group({
items: this.formBuilder.array([this.createItem()])
})
}
createItem(): FormGroup {
return this.formBuilder.group({
checked: true
})
}
addDynamicCheckBox() {
this.items = this.orderForm.get('items') as FormArray;
this.items.push(this.createItem());
}
setCheckBoxValue() {
this.items = this.orderForm.get('items') as FormArray;
this.items.push(this.formBuilder.group({
checked: true,
}))
}
}
模板
<div [formGroup]="orderForm">
<div class="row" formArrayName="items" *ngFor="let item of orderForm.get('items').controls; let i=index">
<div class="col-8" [formGroupName]="i">
<input type="checkbox" formControlName="checked" />
I'm {{item.controls.checked.value === true ? "Checked" : "Unchecked"}}
</div>
</div>
<button (click)="setCheckBoxValue()">Add</button>
</div>