I've this form:
this.myform= new FormGroup({
...
customDetails: new FormArray([]),
});
get customDetailsFormArray() {
return this.shippingLocationDetailsUpdateForm.get(
'customDetails'
) as FormArray;
}
this.customDetailsFormArray.push(
new FormGroup({
customRegNumber: new FormControl(''),
customCode: new FormControl(''),
customRegistrationtype: new FormControl(''),
customRegStartDate: new FormControl(''), // <----------- disable this when user clicks a button
customRegEndDate: new FormControl(''),
})
);
this.myform.enable();
I want to disable customRegStartDate
on click of a button. Rest should remain enabled.
I tried:
this.myform.get('customDetails.customRegStartDate')?.disable();
Tried this also:
Object.entries(this.myform.controls)
.filter(
([key, value]) =>
[
'customDetails.customRegStartDate',
].indexOf(key) < 0
)
.forEach(([key, value]) => value.disable());
But code is not working. Please help.
CodePudding user response:
this.myform.get('customDetails.customRegStartDate')?.disable();
I think AbstractControl#get
doesn't work with these .
separated queries for controls, but you have to query each level separately.
Additionally, this.myform.get('customDetails')
will return a FormArray
, which doesn't have a field customRegStartDate
. You can get the controls with FormArray#controls
(docs).
Then, since with this.customDetailsFormArray.push
you pushed a single item into that, you have to retrieve that with [0]
, which should give you a FormGroup
, the one that has the controls customRegNumber
, customCode
, etc, and also the one you are looking for: customRegStartDate
.
On that you should be able to call disable()
.
EDIT:
Maybe your snippet doesn't show all of the intricacies of the form, but you could possibly change customDetails
from being a FormArray
to be directly the FormGroup
you currently push into that array, ie. you could remove the array level from the form hierarchy.
CodePudding user response:
You need to provide the (FormGroup
) index to disable the selected customRegStartDate
for particular FormGroup
in customDetails
FormArray
.
<button (click)="disableCustomRegStartDateControl(i)">Disable customRegStartDate control</button>
disableCustomRegStartDateControl(i: number) {
this.shippingLocationDetailsUpdateForm
.get(`customDetails.${i}.customRegStartDate`)
?.disable();
}
For disabling all customRegStartDate
controls in FormArray
:
disableAllCustomRegStartDateControl() {
for (let formGroup of this.customDetailsFormArray.controls) {
formGroup.get('customRegStartDate')?.disable();
}
}