Initialize Form Array With existing array in angular reactive form

这一生的挚爱 提交于 2019-11-30 09:54:00

try this, prepare an array of object that contain selected and non selected element

let departmentControl = <FormArray>this.userForm.controls.departmentList;

this.yourArray.forEach(department => {
  control.push(this.fb.group({name: department.yourProperty}))
})

To pre-populate data, there are two methods of FormGroup instance. setValue() & patchValue(). After you receive the response from the server just set/patch the values using one of these methods setValue() and patchValue() both sets the value in form control of FormGroup. setValue() sets the value for each and every form control of FormGroup. you cannot omit any form control in setValue() but if you want to assign only few form controls of FormGroup then you can use patchValue().

 UpdateForm(){
        this.userForm.setValue(
                 {
                    'phone' : '112345',//some Value
                   'departmentList': this.this.departmentList

                });
    }

OR use patchValue(). If you want to update a partcular formControl

  UpdateForm(){
            this.userForm.patchValue(
                     {

                       'departmentList': this.departmentList

                    });
        }

Try This..

let departmentControl = this.form.get('departmentList') as FormArray).controls;

then when you receive response from server then do

I am assuming data in the form of array in data['departmentListdata']

data['departmentListdata'].forEach((department) => { this.departmentList.push(this.createDepartment(department)) 
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!