Angular 2 disable / enable reactive form element on load

I have a dynamic reactive form component. You pass it a set of fields and builds the form.

My problem occurs when I have a checkbox element that controls whether another element on the same form is enabled or disabled. I have no problem updating the sibling when the checkbox of the control is changed, but loading the view gets a good old error ExpressionChangedAfterItHasBeenCheckedError

(obviously only in dev)

public ngOnInit() {
    // If the element is a field controller subscribe to it value changes
    if (this.elementVal.isFieldController === true) {
        // This is what 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

can control one or more values, so I go through each one and disable or enable the field in which 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();
        });
    }
}

      

Since I am doing this onInit

, I am getting the above error, I tried adding in detectChanges()

, and I tried different lifecycle hooks, but for life I can’t solve the problem. Any help would be greatly appreciated.

+3


source to share


1 answer


So I added the bottom lifecycle hook with detection changes and it seems to fix my problem, maybe it helps someone else.



constructor(private cd: ChangeDetectorRef) {}

public ngAfterViewInit() {
    this.cd.detectChanges();
}

      

+4


source







All Articles