Reputation: 8568
I have a material dropdown inside my ngForm, when I set this select as required it shows an asterisk * beside it but the form is seen as valid if I don't select any option from the dropdown.
<mat-form-field class="col-4 offset-1">
<mat-select placeholder="Some placeholder" [(value)]="data.name" required>
<mat-option *ngFor="let name of names" [value]="name.value">
name.viewValue
</mat-option>
</mat-select>
</mat-form-field>
This is unlike what happens if I set the material input to required which will make the form invalid if it is empty.
<mat-form-field class="col-4 offset-1">
<input matInput name="dob" placeholder="Date Of Birth" [(ngModel)]="data.dob" required>
</mat-form-field>
I prefer to solve this using a template driven approach not by using ReactiveForms ( I found some solution talking about the ReactiveForms), can anyone help me?
Note:
I found a question of similar title but it is using FormGroup (reactiveForms)
I have put an example to give an idea in this stackblitz
Upvotes: 8
Views: 30373
Reputation: 11000
You added required
to the select's option
, not the select
. Do it like:
<mat-form-field>
<mat-select placeholder="Favorite food" name="select" [(ngModel)]="select" required>
<mat-option *ngFor="let food of foods" [value]="food.value" >
{{ food.viewValue }}
</mat-option>
</mat-select>
</mat-form-field>
Upvotes: 8
Reputation: 8568
Based on the excellent answer of (from zero to hero), I want to clarify 2 points mentioned in comments:
1- You have to use ngModel not value
2- You have to give the control a name
Full credit goes to him, I wanted to clarify this to any newcomer like me as it took me 2 hours to find out why it doesn't work
Upvotes: 8