mat-select required validation not working

user3097695 picture user3097695 · Mar 29, 2018 · Viewed 29.7k times · Source

I have the following code

<form #createForm="ngForm">
 <mat-form-field>
   <mat-select placeholder="Favorite food"
      matInput
     [ngModel]
     food="food"
     #food="ngModel" required>
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{ food.viewValue }}
    </mat-option>
   </mat-select>
</mat-form-field>
</form>
<button [disabled]="!createForm.valid">submit</button>

Since I want the "selection" is a required field, the "submit" button should be disabled when the form is rendered. However, the "submit" button is enabled when the form is displayed. What is the problem?

Answer

Merenzo picture Merenzo · Jun 29, 2018

This works for me when I (a) use a name attribute and (b) use the two-way ngModel binding syntax.

i.e. Instead of this

<mat-select placeholder="Favorite food" matInput [ngModel] food="food" #food="ngModel" required>

use this:

<mat-select name="food" placeholder="Favorite food" [(ngModel)]="food" required>