You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. 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".
  2. Misplaced matInput directive: The matInput directive 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's food property, which is essential for ngForm to track the control's validity state.
  • Removed matInput directive: We took out matInput since 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 the food variable in your *ngFor loop (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 createForm will correctly recognize the mat-select as a required control, updating its valid state as soon as a value is chosen.

内容的提问来源于stack exchange,提问作者user3097695

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:42:34