使用角度反应形式的现有数组初始化表单数组 [英] Initialize Form Array With existing array in angular reactive form
本文介绍了使用角度反应形式的现有数组初始化表单数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个从服务器获取的动态部门列表数组.我想在初始化时推送该数组以形成数组,基本上我想根据数组中的部门名称或 id 显示复选框.我知道如何以反应形式推送一个空数组.但是如何使用现有数组进行初始化.实际上它是一个更新/编辑组件
departmentList:any=[];//数组包含所有部门SelectedDeptList:any=[];//从数据库中获取,选定的部门用户表单:表单组;this.userForm = this.fb.group({//fb 表单生成器'电话':[空],'部门列表':this.fb.array([this.createDepartment()]),})createDepartment(): FormGroup {返回 this.fb.group({'name': ''//复选框值真或假});}
模板
<div class="form-group"><div class="col-md-4"><label class="mt-checkbox mt-checkbox-outline"><input formControlName="name";类型=复选框">部门名称<span></span>标签>
待办事项?
- 我如何填充或初始化所有部门复选框的列表,以及那些应该是真实存在或存在于我的SelectedDeptList"数组(从数据库中获取)的列表.
提前致谢,任何建议将不胜感激.
解决方案
试试这个,准备一个包含选中和未选中元素的对象数组
let departmentControl = <FormArray>this.userForm.controls.departmentList;this.yourArray.forEach(部门 => {DepartmentControl.push(this.fb.group({name: Department.name}))})
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
});
}
Template
<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>
ToDo ?
- 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屋!