I wrote the below code snippet, which I considered as it will disable the FormControl
in a FormArray
.
some.component.html
<form [formGroup]="testForm">
<div *ngFor="let num of countArr">
<input type="text" formNameArray="arrs">
</div>
</form>
some.component.ts
countArr = [1, 2, 3, 4, 5];
count = 5;
arrs;
testForm: FormGroup;
this.testForm = this.formBuilder.group(
arrs: this.formBuilder.array([])
);
this.arrs = this.testForm.get('arrs');
for (let i = 0; i < this.count; i++) {
this.arrs.insert(i, new FormControl({value: '', disabled: true}));
}
But after for
execution completed, I checked the form and found nothing has been disabled. Can you please tell me where I am doing wrong??? :-)
Thank you for your help!!! :-)
First of all, this is how your html component should look like:
<form [formGroup]="testForm">
<div formArrayName="arrs">
<div class="form-group" *ngFor="let arrItem of testForm.get('arrs').controls; let i = index">
<input type="text" class="form-control" [formControlName]="i">
</div>
</div>
</form>
You do not need to iterate some random count variable inside your html component. You can iterate your added controls.
You may ask "Which controls exactly? They are not added yet!"
Well, this is why you programatically add those controls in ngOnInit
:
ngOnInit() {
this.testForm = new FormGroup({
arrs: new FormArray([])
}
);
for (let i = 0; i < this.count; i++) {
const control = new FormControl(null, Validators.required);
(<FormArray>this.testForm.get('arrs')).push(control);
}
this.disableInputs();
}
This is the corrent syntax to initiate the FormArray
and then create an initial control inside the for
loop and push the newly created control to your array.
Note: there is a disableInputs()
function call. This is where you disable your inputs programatically as well:
disableInputs() {
(<FormArray>this.testForm.get('arrs'))
.controls
.forEach(control => {
control.disable();
})
}
A working sample: stackblitz