用角反应形式的现有阵列初始化表格阵列 [英] Initialize Form Array With existing array in angular reactive form

查看:78
本文介绍了用角反应形式的现有阵列初始化表格阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an dynamic array of department list fetched from server. I want to push that array to form array on initialization, basically i want to show checkboxes based on department name or id in array. I know how to push an empty array in reactive forms.but how to initialize with an existing array.Actually its an update/edit Component

 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

        });
    }

模板

 <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>

待办事项?

1)我该如何填充或初始化所有dept复选框的列表,那些应该为true的"SelectedDeptList"数组(从db获取)中存在或存在的复选框.

1) how can i populate or initialize list of all dept checkboxes and those should be true which are present or exist in my 'SelectedDeptList' array(fetched from db).

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

thanks in advance , any suggestion will be appreciated.

推荐答案

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

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 => {
  departmentControl.push(this.fb.group({name: department.name}))
})

这篇关于用角反应形式的现有阵列初始化表格阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆