Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在编辑页面上预填充表格-Angular4_Angular - Fatal编程技术网

在编辑页面上预填充表格-Angular4

在编辑页面上预填充表格-Angular4,angular,Angular,我有一个angular4表单,它是使用FormBuilder构建的。代码如下 <div *ngFor="let account of accounts"> <input type="checkbox" (change)="onChange(account.id, $event.target.checked)">{{account.id}} {{account.acc_name}}<br> </div&

我有一个angular4表单,它是使用FormBuilder构建的。代码如下

<div *ngFor="let account of accounts">
              <input type="checkbox" (change)="onChange(account.id, $event.target.checked)">{{account.id}}  {{account.acc_name}}<br>
            </div>
initializeFromControls(){
设obj={
名字:新表单控件(“”,),
姓氏:新表单控件(“”,),
电子邮件:new FormControl(“”,
[验证器。必需,
模式(“^[a-z0-9.\%+-]+@[a-z0-9.-]+\[a-z]{2,4}$”),
状态:新表单控件(“”,),
角色id:new FormControl(“”),
帐户标识:this.formBuilder.array([])
}
this.userFrm=this.formBuilder.group(obj);
}
现在我有了另一个名为account_id的字段,它是一个数组。帐户ID是从getAccounts api调用获取的

ngOnInit(){
this.initializeFromControls();
这个.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());
  }
onChange(帐户id:string,isChecked:boolean){
const accountIdArray=this.userFrm.controls.account\u id;
如果(已检查){
accountIdArray.push(新表单控件(帐户id));
}否则{
让index=accountIdArray.controls.findIndex(x=>x.value==account\u id)
accountIdArray.removeAt(索引);
}
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>

{{account.id}{{account.acc_name}}

您知道如何实现这一点吗?

您的初始化很好。 下面是我在编辑页面上必须预先填充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));
})
也许您可以阅读此内容以预填充输入。根据您选择的数据模型,有不同的方法,例如:[(ngModel)],[value]或formControlName属性