为了显示API对模板文件的响应,我使用了反应形式。我的项目要求是,如果API响应包含一些数据,然后显示它,我也可以添加动态数据,所有这些数据都应存储在DB中。如果API响应为空,那么我也可以添加动态数据,该数据也将存储在数据库中。
使用表单数组,下面是我的代码:
ts文件:
orderForm: FormGroup;
items: FormArray;
ngOnInit() {
if(this.data.data && this.data.data.length) {
this.orderForm = this.formBuilder.group({
items: this.formBuilder.array([ ])
})
this.setCheckBoxValue()
}
else {
this.createBlankItem();
}
}
setCheckBoxValue() {
this.items = this.orderForm.get('items') as FormArray;
this.data.data.forEach((element) => {
this.items.push(this.formBuilder.group({
checked: element,
selected: true
}))
});
}
createBlankItem(): FormGroup {
return this.formBuilder.group({
checked: '',
selected: false
})
}
removeDynamicCheckBox(i) {
this.items.removeAt(i);
}
addDynamicCheckBox() {
this.items = this.orderForm.get('items') as FormArray;
this.items.push(this.createItem());
}
模板文件:
<div [formGroup]="orderForm">
<div formArrayName="items" *ngFor="let item of orderForm.get('items').controls; let i=index">
<div class="row" [formGroupName]="i">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<mat-checkbox [formControl]="item.controls.checked.value" class="ml-a" [checked]="item.controls.selected.value">
</mat-checkbox>
</div>
<div class="col-lg-10 col-md-10 col-sm-10 col-xs-10">
<mat-form-field
floatPlaceholder="never" class="margin-top-25px example-full-width" >
<input
matInput
class="input"
value="{{item.controls.checked.value}}"
>
</mat-form-field>
</div>
<!-- <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<a href="" (click)="removeDynamicCheckBox(i)">X</a>
</div> -->
</div>
</div>
</div>
<div class="row">
<button mat-raised-button (click)="addDynamicCheckBox()">Add</button>
</div>
我得到了想要的东西,但是在控制台中,我得到了这个错误:
错误TypeError:无法在字符串上创建属性“验证器”
请帮帮我。
答案 0 :(得分:0)
在复选框HTML输入中,重写formControl指令。
<mat-checkbox [formControl]="item" class="ml-a" [checked]="item.controls.selected.value">
</mat-checkbox>
还要在ts文件中,修改setCheckBoxValue方法以添加FormControl而不是FormArray
setCheckBoxValue() {
this.items = this.orderForm.get('items') as FormArray;
this.data.data.forEach((element) => {
let control = new FormControl(true);
this.items.push(control)
});
}