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

Angular Material 必填复选框验证:实现表单提交后未触碰红色提示

解决Angular Material必填复选框提交后未触碰时的红色验证样式问题

我明白你想要让必填复选框和Angular Material其他表单控件保持一致的验证体验——表单提交后,未被用户触碰过的未勾选复选框要显示红色错误样式。之前用ng-style卡壳在没法判断表单是否提交,下面给你一套完整的实现方案:

1. 先在组件类里跟踪表单提交状态

我们需要添加一个布尔变量来记录表单是否被提交过,然后在提交方法里更新这个状态:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CreateProfileComponent } from '../create-profile.component';

@Component({
  selector: "step-five-component",
  templateUrl: "./step-five.component.html",
  styleUrls: ["../create-profile.component.css"]
})
export class StepFiveComponent {
  frmFinish: FormGroup;
  stepFive = { note: null };
  formSubmitted = false; // 新增:标记表单是否已提交

  constructor(private formBuilder: FormBuilder) {
    this.frmFinish = this.formBuilder.group({});
  }

  ngOnInit() {
    this.frmFinish = this.formBuilder.group({
      note: ['', Validators.required],
      check1: ['', Validators.required],
      check2: ['', Validators.required],
      check3: ['', Validators.required],
    });
  }

  createProfile(){
    this.formSubmitted = true; // 提交时把状态设为true
    if(this.frmFinish.valid){
      console.log('Creating profile..');
    }else{
      // 表单无效,此时错误样式会自动生效
    }
  }

  fillForm(){
    this.stepFive.note = 'asdasd';
  }
}

2. 在HTML里给复选框绑定条件样式

给每个mat-checkbox添加类绑定,当表单已提交、控件无效且未被触碰时,应用自定义错误样式:

<form [formGroup]="frmFinish" name="frmFinish" (ngSubmit)="createProfile()">
  <mat-checkbox 
    required 
    formControlName="check1"
    [class.invalid-checkbox]="formSubmitted && frmFinish.get('check1').invalid && frmFinish.get('check1').untouched"
  >
    Discussed Confidentiality and Information Sharing with Service User
  </mat-checkbox>

  <mat-checkbox 
    required 
    formControlName="check2"
    [class.invalid-checkbox]="formSubmitted && frmFinish.get('check2').invalid && frmFinish.get('check2').untouched"
  >
    Discussed Disposal and Storage of Injecting Equipment and Substances
  </mat-checkbox>

  <mat-checkbox 
    required 
    formControlName="check3"
    [class.invalid-checkbox]="formSubmitted && frmFinish.get('check3').invalid && frmFinish.get('check3').untouched"
  >
    Discussed Overdose Risk and Prevention
  </mat-checkbox>

  <mat-form-field>
    <textarea formControlName="note" [(ngModel)]="stepFive.note" matInput placeholder="Any Additional Notes" matTextareaAutosize matAutosizeMinRows="2" matAutosizeMaxRows="5"></textarea>
    <mat-hint align="end">This will be added to the profiles note's</mat-hint>
  </mat-form-field>

  <mat-card-actions>
    <button mat-raised-button type="button" class="nav-btn pull-right" (click)="fillForm()" style="background: red">Fill Form</button>
    <button mat-raised-button class="nav-btn pull-right" style="margin-left:5px;" type="submit">Finish</button>
    <button mat-raised-button matStepperPrevious class="nav-btn pull-right">Previous</button>
  </mat-card-actions>
</form>

小优化:我给表单加了(ngSubmit)="createProfile()"事件,点击"Finish"按钮(type="submit")时触发提交,这比单独绑定click事件更符合Angular表单的规范。

3. 添自定义CSS匹配Material错误样式

在组件的CSS文件里添加样式,让复选框的错误效果和其他Material控件保持一致:

/* 未勾选且需要显示错误时的样式 */
.invalid-checkbox .mat-checkbox-frame {
  border-color: #f44336; /* Material Design默认错误红色 */
}

.invalid-checkbox .mat-checkbox-label {
  color: #f44336;
}

/* 用户触碰过复选框后,移除错误样式 */
.invalid-checkbox.ng-touched .mat-checkbox-frame {
  border-color: initial;
}

.invalid-checkbox.ng-touched .mat-checkbox-label {
  color: initial;
}

这套方案的核心就是通过formSubmitted变量精准判断表单提交状态,再结合控件的invalid和untouched状态,给需要的复选框加上错误样式,完美匹配Angular Material其他控件的验证体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:37:22