The issue
Encountering an
ExpressionChangedAfterItHasBeenCheckedError
error while using a PasswordComponent
with ng-template
. Specifically, wanting to conditionally bind the errorStateMatcher
only when controlName === 'confirmPassword'
.
To view the complete code causing the problem, visit here. Look inside password.component.html
for the troublesome ng-template
:
<template *ngIf="controlName === 'confirmPassword'; then Custom else Default"></template>
<ng-template #Custom>
<input matInput [placeholder]="placeholder" [formControlName]="controlName" [type]="showPassword ? 'text' : 'password'" [autocomplete]="autocomplete" [errorStateMatcher]="errorMatcher"/>
</ng-template>
<ng-template #Default>
<input matInput [placeholder]="placeholder" [formControlName]="controlName" [type]="showPassword ? 'text' : 'password'" [autocomplete]="autocomplete"/>
</ng-template>
Note: Even without the
ng-template
, placing thengIf
directly on theinput
element still triggers the same error. Initially believed to be associated withng-template
but it's actually related tongIf
.
The Error
The mat-error
values are inconsistent and occasionally display aria-describedby: null
.
PasswordComponent.html:4 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression changed after it was checked. Previous value: 'aria-describedby: mat-error-3'. Current value: 'aria-describedby: mat-error-4'.
Error Reproduction Steps
- Enter text in password field
- Switch focus back to username input
- Return focus to password input
- Edit or remove characters to change the
mat-error
message - Console will show
ExpressionChangedAfterItHasBeenCheckedError