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

Angular Material输入框报错时添加图标:实现方案求助

问题需求

希望在mat input字段校验报错时,在清除字段图标旁添加一个错误图标,效果如下:
错误图标效果

目前找不到添加该图标的方法,现有的代码如下:

HTML代码

<button
    *ngIf="value"
    matPrefix
    mat-icon-button
    aria-label="Clear"
    (click)="value = ''"
>
    <mat-icon>highlight_off</mat-icon>
    کلمه جدید 
</button>
<input
    class="word-input"
    matInput
    type="text"
    [(ngModel)]="value"
    id="word"
    #wordInput="ngModel"
    required
/>
<mat-error>
    کلمه ورودی قبلا وارد شده‌است
</mat-error>

CSS代码

::ng-deep .mat-error {
    text-align: right;
    font-size: 12px;
}

:host ::ng-deep .mat-form-field-appearance-outline.mat-form-field-invalid .mat-form-field-outline-thick,
:host ::ng-deep .mat-form-field.mat-form-field-invalid .mat-form-field-label,
.mat-error {
    color: var(--error) !important;
}
解决方案

要实现这个效果,你可以借助Angular表单的状态判断,在清除按钮旁添加错误图标,具体步骤如下:

  1. 完善表单引用:确保#wordInput="ngModel",这样才能获取输入框的校验状态。
  2. 添加错误图标:用matPrefix(和清除按钮同区域),通过*ngIf判断输入框无效且已被触碰/内容有变化时显示图标。
  3. 调整样式:给错误图标设置错误色和间距,避免和清除按钮重叠。

修改后的HTML代码:

<!-- 清除按钮 -->
<button
    *ngIf="value"
    matPrefix
    mat-icon-button
    aria-label="Clear"
    (click)="value = ''"
>
    <mat-icon>highlight_off</mat-icon>
</button>
<!-- 错误图标 -->
<mat-icon 
    matPrefix 
    *ngIf="wordInput.invalid && (wordInput.touched || wordInput.dirty)"
    class="error-icon"
>
    error
</mat-icon>
<input
    class="word-input"
    matInput
    type="text"
    [(ngModel)]="value"
    id="word"
    #wordInput="ngModel"
    required
/>
<mat-error>
    کلمه ورودی قبلا وارد شده‌است
</mat-error>

添加对应的CSS样式:

::ng-deep .mat-error {
    text-align: right;
    font-size: 12px;
}

:host ::ng-deep .mat-form-field-appearance-outline.mat-form-field-invalid .mat-form-field-outline-thick,
:host ::ng-deep .mat-form-field.mat-form-field-invalid .mat-form-field-label,
.mat-error,
.error-icon {
    color: var(--error) !important;
}

.error-icon {
    margin-right: 8px;
    font-size: 20px;
}

关键说明

  • wordInput.invalid && (wordInput.touched || wordInput.dirty):避免页面刚加载就显示错误图标,只在输入框无效且用户已交互后才展示。
  • matPrefix:保证错误图标和清除按钮处于输入框的同一前缀区域,适配你的布局方向。
  • 样式调整确保错误图标颜色统一,和清除按钮保持合理间距,还原目标效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:20:28