我有多个复选框作为FormArray。当页面加载时,我想禁用所有这些复选框。
我尝试了下面提到的方法,但它没有工作。
谁能给我解释一下吗?。ts文件
public myForm: FormGroup = new FormGroup({
name: new FormControl('', Validators.required),
specialized: new FormArray([]),
});
ngOnInit(): void {
this.companyForm.controls['specialized'].disable();
}
get myFormArray() {
return this.myForm.controls.specialized as FormArray;
}
private addCheckboxesToForm() {
this.specilizedArea.forEach(() => this.myFormArray.push(new FormControl(false)));
}
. html文件
<form [formGroup]="myForm">
<div class="form-check col-md-6"
*ngFor="let order of myFormArray.controls; let i = index">
<label formArrayName="specialized">
<input type="checkbox" [formControlName]="i">
{{specilizedArea[i]?.description}}
</label>
</div>
<button (click)="saveCompany()"> ADD</button>
</form>
在ngOnInit
中,您需要调用方法addCheckboxesToForm
,并在该方法中创建具有disabled: true
属性的FormControls,它应该看起来像这样:
private addCheckboxesToForm() {
this.specilizedArea.forEach(() => this.myFormArray.push(new FormControl({value: false, disabled: true})));
}
下面是我用你的代码创建的快速示例:https://stackblitz.com/edit/angular-ivy-bmnfcd?file=src/app/app.component.ts