用角反应形式的现有阵列初始化表格阵列

nai*_*eem 5 forms angular2-forms angular angular-reactive-forms

我有一个从服务器获取的部门列表的动态数组。我想在初始化时将该数组推入数组,基本上我想根据部门名称或数组中的ID显示复选框。我知道如何以反应形式推送空数组,但是如何使用现有数组初始化。实际上是一个更新/编辑组件

 departmentList:any=[];    //array contains all departments  
 SelectedDeptList:any=[];  //fetched from db , selected departments

userForm: FormGroup; 
this.userForm = this.fb.group({  //fb form builder
                'phone': [null],
                 'departmentList': this.fb.array([this.createDepartment()]),
        })


  createDepartment(): FormGroup {
        return this.fb.group({
            'name': ''//checkbox value true or false

        });
    }
Run Code Online (Sandbox Code Playgroud)

模板

 <div formArrayName="departmentList"
                                *ngFor="let item of 
    userForm.get('departmentList').controls; let i = index;">
   <div class="col-md-6" [formGroupName]="i">
   <div class="form-group">

   <div class="col-md-4">
   <label class="mt-checkbox mt-checkbox-outline">
   <input  formControlName="name" type="checkbox" > Department Name
   <span></span>
   </label>

   </div>
   </div>

   </div></div>
Run Code Online (Sandbox Code Playgroud)

去做 ?

1)我怎么能填充或初始化所有的dept复选框的列表,那些应该是真实的存在或存在于我的“ SelectedDeptList”数组中(从数据库中获取)。

在此先感谢,任何建议将不胜感激。

Fat*_*med 10

试试这个,准备一个包含选定元素和未选定元素的对象数组

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

this.yourArray.forEach(department => {
  departmentControl.push(this.fb.group({name: department.name}))
})
Run Code Online (Sandbox Code Playgroud)


Vik*_*kas 1

要预填充数据,FormGroup 实例有两种方法。setValue()patchValue()。收到服务器的响应后,只需使用这些方法之一设置/修补值setValue(),并且都设置中的patchValue()值。 设置 FormGroup 的每个表单控件的值。您不能省略任何表单控件,但如果您只想分配 FormGroup 的少数表单控件,那么您可以使用form controlFormGroupsetValue()setValue()patchValue().

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

                });
    }
Run Code Online (Sandbox Code Playgroud)

或使用patchValue(). 如果你想更新特定的formControl

  UpdateForm(){
            this.userForm.patchValue(
                     {

                       'departmentList': this.departmentList

                    });
        }
Run Code Online (Sandbox Code Playgroud)