I have a dynamic reactive form component. You pass it a set of fields and it builds a form.
My issue comes when I have a checkbox element that controls whether another element within the same form is enabled or disabled. I have no issue with updating the sibling element when the control checkbox is changed but when the view is loaded I get the good old ExpressionChangedAfterItHasBeenCheckedError error (only in dev obviously)
public ngOnInit() {
// If the element is a field controller subscribe to it's value changes
if (this.elementVal.isFieldController === true) {
// This is what's causing the issue
this.toggleControlledFields(this.form.get(this.elementVal.key).value);
this.form.get(this.elementVal.key).valueChanges
.subscribe((data) => {
console.log(data, 'the data');
this.toggleControlledFields(data);
});
}
}
A fieldController may control one or more values so I loop through each one and disable or enable the field it controls:-
public toggleControlledFields(value) {
if (value === '' || value === false) {
this.elementVal.fieldsToControl.forEach((field) => {
this.form.get(field).disable();
});
} else {
this.elementVal.fieldsToControl.forEach((field) => {
this.form.get(field).enable();
});
}
}
Because I do this onInit I get said error, I've tried adding in a detectChanges() and I've tried different lifecycle hooks but for the life of me can't solve the problem. Any help would be greatly appreciated.