我正在尝试使用数据库中已有的信息填充Angular表单。我可以将其用于输入“范围”和“文本”,但无法弄清楚如何对“复选框”进行此操作。
这里是我所拥有的一个例子:
this.form = this.fb.group({
option: this.fb.group({
numbers: this.fb.array([]),
name: ['', Validators.required]
}),
selectedCount = 0;
maxCount = 3;
preference = {
options: ['West',
'East',
'Midwest',
'Southwest',
'Southeast',
'Northeast']
};
inArray(option: string) {
const formArray = this.form.get('option').get('numbers') as FormArray;
return formArray.value.includes(option);
}
onChange(option: string, isChecked: boolean) {
const formArray = this.preferencesForm.get('option').get('numbers') as FormArray;
if (isChecked) {
formArray.push(new FormControl(option));
this.selectedCount++;
} else {
const index = formArray.controls.findIndex(x => x.value === option);
formArray.removeAt(index);
this.selectedCount--;
}
}
<div formGroupName="option">
<div *ngFor="let option of preference.options">
<input
type="checkbox"
(change)="onChange(option, $event.target.checked)"
[disabled]="(selectedCount >= maxCount) && !inArray(option)"
id={{option}}, name={{option}}>
<label for='{{option}}'> {{option}} </label>
</div>
</div>
<input type="text" name="name" id="name" required formControlName="name">
</div>
</div>
最后,这就是我试图填充表格的方式。我有userPref,它具有来自后端的信息。我能够填充“文本”输入字段,但无法获得复选框
populateInfo() {
const formControls = this.form.controls;
const userPref = this.user.user_pref;
console.log('user ', userPref);
console.log('pref form ', preferenceFormControls)
formControls.option.get('name').setValue(userPref.name);
userPref.numbers.forEach( (num) => {
(formControls.option.get('numbers') as FormArray).push( this.fb.control(num) )
});
}
这将使用userPref信息正确填充“名称”(表明我正确提取了信息)这会将userPref编号添加到表单数组。我可以在浏览器终端上看到。但是,我不知道如何显示已选中的框。
这是一篇很长的文章,所以请先感谢!
您的想法有点复杂。希望这会有所帮助:
const dataFromBE = .... // get the data from BE
this.form = this.fb.group({
numbers: new FormArray(this.preference.options.map(x => dataFromBE.includes(x))),
name: new FormControl('', [Validators.require]),
});
在HTML中:
<div formArrayName="numbers">
<input
*ngFor="let opt of form.get('numbers').controls; let i = index"
[formControlName]="i"
type="checkbox"
/>
<label> {{preference.option[i]}} </label>
</div>
最后提交表单后,您将获得数据:
const value = this.form.get('numbers').value as [];
//value is an array of boolean, but if you need the value see below
console.log(value.map((x, i) => x ? this.preference.options[i] : null).filter(x => x))