I want to add validations to mat-select where the user needs to select at least one entry
html file:
<mat-form-field>
<mat-label>Select drink(s):</mat-label>
<mat-select [formControl]="drinks" multiple (selectionChange)="checkSelectedDrinks($event.value)">
@for (drink of drinkList; track drink) {
<mat-option [value]="drink">{{drink}}</mat-option>
}
</mat-select>
<mat-error *ngIf="drinkSelectionErr">
You need to select at least one drink
</mat-error>
</mat-form-field>
ts file:
drinkList: string[] = ["A","B","C","D","E"];
drinks = new FormControl(this.drinkList);
checkSelectedDrinks(selectedDrinks: string[]){
if (!selectedDrinks.length){
this.drinkSelectionErr = true;
}
}
The code above does nothing when all drinks are unselected from the drop down menu.
3
Answers
I found the solution:
For mat-error, I updated the 'if' condition to use the fromControl status attribute
You are not setting any validators. Remove the
onchange
and add a validator.Then the control will be marked invalid when nothing is selected and you can display it in the HTML.
Note that your validator could return multiple errors, in which case, you’d need to switch between possible error codes (
must.select.item
) to display the correct error message.Here is a working example for your reference, we can just use the
required
validator of angular!ts
html
stackblitz