Skip to content

Instantly share code, notes, and snippets.

@hollygood
Last active April 17, 2019 19:34
Show Gist options
  • Save hollygood/a6ac8b0311e35349d6e5b3743806c9fc to your computer and use it in GitHub Desktop.
Save hollygood/a6ac8b0311e35349d6e5b3743806c9fc to your computer and use it in GitHub Desktop.
ExpressionChangedAfterItHasBeenCheckedError

mat-form-field causes Error: ExpressionChangedAfterItHasBeenCheckedError

link: angular/components#12714

I also got the same error by using mat-form-field in ng-bootstrap modal:

"ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'mat-form-field-should-float: false'. Current value: 'mat-form-field-should-float: true'."

ChangeDetectionStrategy.OnPush doesn't work for me.

The reason for this is when open a new dialog, the ng-bootstrap modal auto focus on the first focusable element within modal, which is my first mat-form-field, and the mat-form-field-should-float value change from 'false' to 'true' because of the focus event. I manage to resolve this issue by moving the focus to other element instead of mat-form-field by using 'ngbAutofocus'.

example:

//--- the following code is within a ng-bootstrap modal
<button ngbAutofocus>View</button>

<form>
  <div class="form-group">
        <mat-form-field>
            <mat-label>Test Field</mat-label>
            <input
                matInput
                type="text"
                formControlName="test"

            />
        </mat-form-field>
    </div>
</form>

or if you click a button and open the dialog, you can use the following:

event.srcElement.blur();
event.preventDefault();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment