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

Angular响应式表单:让已触碰且无效的表单字段显示红色边框

解决方案

Angular Material 15基于MDC(Material Design Components)重构了组件结构,原有的宽泛CSS选择器会误选中表单字段内的提示文本等无关元素,你需要精准定位输入框/文本域元素来设置样式:

基础填充型表单字段样式

仅在字段同时处于touched和invalid状态时,给输入框、文本域添加红色边框:

/* 匹配输入框和文本域元素 */
.mat-mdc-form-field.mat-mdc-form-field-invalid.mat-mdc-form-field-touched :is(.mdc-text-field__input, .mdc-text-field__textarea) {
  border: 1px solid red;
}

Outline型表单字段样式

如果你的表单字段使用了appearance="outline"样式,需要修改外层轮廓的边框颜色:

.mat-mdc-form-field.mat-mdc-form-field-invalid.mat-mdc-form-field-touched .mdc-text-field--outlined .mdc-notched-outline__leading,
.mat-mdc-form-field.mat-mdc-form-field-invalid.mat-mdc-form-field-touched .mdc-text-field--outlined .mdc-notched-outline__notch,
.mat-mdc-form-field.mat-mdc-form-field-invalid.mat-mdc-form-field-touched .mdc-text-field--outlined .mdc-notched-outline__trailing {
  border-color: red;
}

核心说明

  • 放弃.ng-invalid:not(form)这类宽泛选择器,改用Material 15新增的mat-mdc-form-field-invalid、mat-mdc-form-field-touched类定位表单容器,再精准选中内部输入元素,避免影响其他组件。
  • 建议将代码放在组件专属样式文件中,若用全局样式需确保选择器优先级足够覆盖默认样式。

内容的提问来源于stack exchange,提问作者shine-dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 14:19:56