【问题标题】:Angular - reactive form - material - color icon when invalid角度 - 反应形式 - 材料 - 无效时的颜色图标
【发布时间】:2023-03-20 17:47:01
【问题描述】:

我正在 Angular(使用 Material)中准备响应式表单,当字段无效时,我会为图标着色。

component class

wholeForm = new FormGroup({
...
contact: new FormGroup({
  ...
  city: new FormControl('', [Validators.required])
}),
...

});

component html template

<form [formGroup]='wholeForm' (ngSubmit)='onSubmit()'>
...
<div class="form-group" formGroupName="contact">

    ...
          <div class='code-city'>
        <mat-form-field>
          <input formControlName="postalCode" matInput maxlength="5" placeholder="postal code*">
        </mat-form-field>
        <mat-form-field>
          <input formControlName="city" matInput placeholder="city*">
        <mat-icon matSuffix>location_on</mat-icon>
        </mat-form-field>
          </div>

我尝试在city 输入和mat-icon [class.red-icon]='city.invalid' 中添加一些本地引用,但没有成功。接下来我还尝试将类绑定到类中的属性,但没有结果。

当我硬编码为wholeForm.valid 时,CSS 类有效。

CSS

.red-icon{
 color: red;
}

【问题讨论】:

    标签: angular validation angular-material angular-reactive-forms


    【解决方案1】:

    试试

    [class.red-icon]="wholeForm.controls.contact.controls['city'].invalid && wholeForm.controls.contact.controls['city'].touched"
    

    【讨论】:

    • 正确答案。特别适用于单一和出色的输入验证。我标记了不同的解决方案,因为那更普遍。您的答案显示了进入表单属性的方法。这真好!你能告诉我你为什么使用“controls.contact”和下一个“controls['city']”吗?有什么区别吗?我看到了,当我使用'。 IDE 向我显示一些错误(但它有效),当我使用“['...']”时,IDE 没有显示任何内容,它仍然有效。
    • 正如你所说,当我们使用 '.' 时 IDE 显示错误这是因为打字稿在运行前检查错误,当我们使用“['...']”打字稿无法检测到对象并认为它是正确的,但是当我们使用'。'它可以找到对象层次结构并显示错误。但两者在运行时都是正确的。
    • 所以一般我什么时候应该使用'.'什么时候“['...']”?
    • 根据我的经验,当我们可以完全访问我们的对象接口类型时,我们可以使用'.'并以其他方式使用 "['...']" ,但不确定,请使用 IDE 进行检查:D
    【解决方案2】:

    使用此代码,

    <div class='code-city'>
        <mat-form-field>
            <input formControlName="postalCode" matInput maxlength="5" placeholder="postal code*">
        </mat-form-field>
        <mat-form-field>
            <input formControlName="city" matInput placeholder="city*">
            <mat-icon matSuffix>location_on</mat-icon>
        </mat-form-field>
     </div>
    

    style.css

    .mat-form-field-invalid .mat-icon {
        color: red;
    }
    

    【讨论】:

    • 是的,它适用于所有无效的 mat-form-field,如果这对您有帮助,请投票。
    猜你喜欢
    • 2022-11-25
    • 2020-05-19
    • 1970-01-01
    • 2020-01-15
    • 2019-02-28
    • 2023-03-06
    • 2019-07-01
    • 2019-12-25
    • 2015-08-13
    相关资源
    最近更新 更多