Highlight mat-form-field on invalid value without [(ngModel)]

1.1k Views Asked by At

I have a mat-form-field with the following input inside of a form :

<input matInput name="input" type="number" step="any" (input)="doSomething()" required />

The input is marked as required but is not highlighted in red when emptied : mat-form-field not highlighted even though invalid

But if I had a binding with [(ngModel)] like below, the red highlight appears : mat-form-field correctly highlighted

<input matInput name="input" type="number" step="any" (input)="doSomething()" required [(ngModel)]="whyDoINeedThis"  />

Is there a way I can avoid having to bind to a useless variable just to get invalid highlights without having to mark the field as invalid manually or do the styling myself ?

1

There are 1 best solutions below

0
On

When Setting your form in ts, try giving the control a required validator.

the form in your ts should have this.

input = new FormControl('', [Validators.required]);