我有一个 angular4 表单,它是使用表单生成器构建的。代码如下。
initializeFromControls() {
let obj = {
firstname: new FormControl('', ),
lastname: new FormControl('', ),
email: new FormControl('',
[Validators.required,
Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")]),
status: new FormControl('', ),
role_id: new FormControl(''),
account_ids: this.formBuilder.array([])
}
this.userFrm = this.formBuilder.group(obj);
}
现在我有另一个名为 account_ids 的字段,它是一个数组。帐户 ID 是从 getAccounts API 调用中获取的。
ngOnInit() {
this.initializeFromControls();
this.getAccounts();
}
使用以下代码将选定的帐户 ID 发送到后端。
onChange(account_id:string, isChecked: boolean) {
const accountIdArray = <FormArray>this.userFrm.controls.account_ids;
if(isChecked) {
accountIdArray.push(new FormControl(account_id));
} else {
let index = accountIdArray.controls.findIndex(x => x.value == account_id)
accountIdArray.removeAt(index);
}
console.log(this.userFrm.getRawValue());
}
现在我需要在编辑页面上预填充帐户 ID (formArray)。
模板如下。
<div *ngFor="let account of accounts">
<input type="checkbox" (change)="onChange(account.id, $event.target.checked)">{{account.id}} {{account.acc_name}}<br>
</div>
知道如何实现这一目标吗?
最佳答案
你的初始化没问题。 在我的例子中,我是如何在编辑页面上预填充 FormArray 的:
items: FormArray;
//response from server
response['data'].map((item, index) => {
const tmpDict = {};
tmpDict['firstname'] = new FormControl(item.firstname);
tmpDict['lastname'] = new FormControl(item.lastname);
tmpDict['email'] = new FormControl(item.email);
this.items = this.userFrm.get('items') as FormArray;
this.items.push(new FormGroup(tmpDict));
})
关于angular - 在编辑页面上预填充 formArray - Angular4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51782076/