5

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.

1 Answer 1

6

So I added the below life cycle hook with a detect changes and that seems to have fixed my issue, maybe this will help someone else..

constructor(private cd: ChangeDetectorRef) {}

public ngAfterViewInit() {
    this.cd.detectChanges();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Saves my day - especially when the update of the DOM-elemnts is dependent on internal validation mechanism!!! THX
Glad it helped you :)
I'm disabling a field in the ctor (i.e. it's never, ever enabled - just there to show the field; I do it before the data is even loaded), and I seem to have to do what you said to avoid the error even though it's not an issue of dynamically changing enable/disable after the data or form has loaded. This is crazy. I must be doing something wrong, right?? This can't be by-design...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.