I have a dialog form where users can add new projects. I want to prevent the save buttons from being enabled until all required fields are filled in correctly. I have an isValid() function that handles this validation and it appears to be working properly. However, I am encountering an issue when checking the console:
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous
value: 'mat-form-field-should-float: false'. Current value: 'mat-form-field-should-float: true'.
The mat-form-field causing the problem is located here:
<mat-form-field class="input-half-width">
<input matInput [formControl]="name" placeholder="Project Name" #nameInput required>
</mat-form-field>
The specific HTML section triggering the error seems to be related to the [disabled]=!isValid() attribute. While removing it resolves the error, maintaining the validation functionality is necessary.
<button mat-raised-button (click)="closeDialog(saveAndContinueIsClicked);">Close</button>
<button mat-raised-button color="primary" [disabled]="buttonIsClicked || !isValid()" (click)="saveAndCloseDialog(false); buttonIsClicked=true; saveAndContinueIsClicked=true;">Save and Continue</button>
<button mat-raised-button color="primary" [disabled]="buttonIsClicked || !isValid()" (click)="saveAndCloseDialog(); buttonIsClicked=true;">Save and Close</button>
This is what my isValid() function looks like:
isValid() {
if (this.projectName.value == null || this.projectName.value == "") {
this.error = 'Name is required';
this.nameElement.nativeElement.focus(); // The error disappears if I remove this line.
return false;
}
In my component, nameElement is defined as follows:
@ViewChild('nameInput')
nameElement: any;
I understand the underlying cause of the issue. Focusing on the name field when the dialog opens causes the label to float, leading to the error. I might consider removing the focus line for the name input but would prefer to find a workaround if possible.