我有一个从DB中获取的技能列表,如下所示:
<div class="uk-margin">
<div *ngFor="let data of skills">
<div *ngFor="let skill of data.allSkills">
<input type="checkbox"> {{skill}}<br>
</div>
</div>
</div>
以上输出:
我的表单模式如下所示:
this.userForm = this._fb.group({
name: ['', [Validators.required]],
skills: this._fb.array([]),
});
然后我获取他们在其他时间选择的登录用户的复选框值。当我使用Reactive Forms
我patch
时,DB为用户返回的值如下:
// Patch Skills
let ctrl = <FormArray>this.userForm.controls.skills;
this.user.skills.forEach(item => {
ctrl.push(new FormControl(item))
});
// Patch Other things
this.userForm.patchValue({
name: this.user.name,
});
如果我console.log(ctrl.controls);
我得到以下内容:
I have a test
I have a nothing
如何自动选择从该用户的数据库返回的复选框项目(以便“我没有任何内容”和“我有一个测试”被自动检查)和还要更新formArray
用户检查或取消选中值,然后再将其发送到数据库?
答案 0 :(得分:0)
如果您的技能包含在checked
ctrl.controls
媒体资源
<div class="uk-margin">
<div *ngFor="let data of skills">
<div *ngFor="let skill of data.allSkills">
<input type="checkbox" [checked]="ctrl.controls.includes(skill)"> {{skill}}<br>
</div>
</div>
</div>
答案 1 :(得分:0)
我认为这会对你有所帮助!
解决方案:
组件代码:
let formArray: Array<any> = [];
for (let skills of data.allSkills) {
formArray.push(new FormControl(skills.value));
}
let formGroup = {};
this.fieldName = 'skillGroup'
formGroup[this.fieldName] = this._formBuilder.array(formArray);
this._fromGroup = this._formBuilder.group(formGroup)
模板:
修改强>