首页 > 解决方案 > Angular 反应形式:无法使用 ngClass

问题描述

我有这个反应式表单输入,我想bottom-border根据其验证添加绿色或红色。在下面的示例中,我只有所需的验证,当输入被触摸并且无效时,我想添加类.invalid-input { bottom-border: 3px solid red}。我尝试了下面的代码,但它不起作用。当我将输入留空并移至另一个输入时,它不会显示任何边框。有人能看出为什么吗?

<input
   id="firstName"
   class="form__input"
   type="text"
   placeholder="First Name"
   (keyup.enter)="getErrors()"
   formControlName="firstName"
   ngClass="{
     'invalid-input': firstName.invalid && (firstName.dirty || firstName.touched)
   }"
>

CSS

.valid-input {
  border-bottom: 3px solid green;
}

.invalid-input {
  border-bottom: 3px solid red;
}

标签: cssangular

解决方案


您不需要使用 ngClass 指令角度反应形式将类添加到任何反应形式控件,因此您可以轻松定位元素的状态。

.ng-invalid.ng-touched , .ng-invalid.ng-dirty{ 
    border-bottom: 3px solid red;
}

在您的问题中,您需要使用 [ngClass]="..." 并 formGroup.controls.firstName立即使用表单控制


推荐阅读