mat-select必填验证不生效问题,附相关代码求助
Fixing mat-select Required Validation Not Working in Angular
Let's break down why your mat-select required validation isn't kicking in, and fix it step by step:
The Issues in Your Code
Looking at your snippet, there are two critical mistakes that are blocking the validation from working as expected:
- Invalid ngModel binding syntax: You wrote
[ngModel] food="food"which is not the correct way to bind the control value. Angular's two-way binding for ngModel uses the syntax[(ngModel)]="food". - Misplaced
matInputdirective: ThematInputdirective is designed for<input>elements inside mat-form-field, not for<mat-select>. Adding it here disrupts the mat-select's built-in validation logic.
Corrected Code
Here's the fixed version of your form and submit button:
<form #createForm="ngForm"> <mat-form-field> <mat-select placeholder="Favorite food" [(ngModel)]="food" #foodCtrl="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>
Key Changes Explained
- Fixed ngModel binding:
[(ngModel)]="food"properly links the select's value to your component'sfoodproperty, which is essential for ngForm to track the control's validity state. - Removed
matInputdirective: We took outmatInputsince it doesn't belong on mat-select. This lets the mat-select's native validation behavior activate correctly. - Renamed template reference: I changed
#food="ngModel"to#foodCtrl="ngModel"to avoid naming conflicts with thefoodvariable in your*ngForloop (this is a best practice to prevent confusion, even if it wasn't the direct cause of the validation failure).
What Happens Now
With these fixes in place:
- The submit button will stay disabled until you select a valid option from the mat-select.
- The
createFormwill correctly recognize the mat-select as a required control, updating itsvalidstate as soon as a value is chosen.
内容的提问来源于stack exchange,提问作者user3097695
相关产品推荐
相关产品推荐

