Search code examples
angularangular-materialangular-reactive-formsmat-steppermat-input

Angular Material custom input validation message not showing with mat-stepper


I implemented custom control based on official guides using ControlValueAccessor:

The issue that validation error is not showing until we touch our custom field. In my case I have an issue with Stepper, but it also not working when I do this.form.markAllAsTouched()

Error example

I provide example below based on official custom Phone field. Click "Next" with empty fields.

Example on stackblitz


Solution

  • See the function errroState. You can add the condition ngControl.invalid and mark as touched is the ngControl is touched using

      get errorState(): boolean {
        const touched=!!this.ngControl?.touched;
        if (touched!=this.touched)
        {
          this.touched=touched;
          this.stateChanges.next();
        }
        return (this.parts.invalid || !!this.ngControl?.invalid) && this.touched;
      }
    

    Then if you mark as touched the FormControl, you see the error

    <button type="button" mat-button matStepperNext 
       (click)="form.markAllAsTouched()" >Next</button>
    

    stackblitz