如何将条件错误检查从 NgIf 移动到打字稿文件?

How to move conditional error checks from NgIf to typescript file?

在我的 Angular 应用程序中,我需要 add/remove CSS 类 根据 FormControl 是否已被触摸、脏、无效等.

我正在使用 ngClass 指令来执行此操作:

<div class="form-group has-required"
    [ngClass]="{'has-error':
        (conditionsForm.get('acceptTerms').touched || conditionsForm.get('acceptTerms').dirty)
         && conditionsForm.get('acceptTerms').errors}">
</div

这是我目前在 Typescript 中的内容:

ngOnInit() {
    this.conditionsForm = this.fb.group({
        acceptTerms: new FormControl('', Validators.required),
        insuredType: new FormControl('', Validators.required),
        reportInjury: new FormControl('', Validators.required)
    });
}

由于上面的条件很长,我想把它移到我的 Typescript 文件中。

有没有特定的方法可以做到这一点?我不确定我该怎么做。有人可以告诉我我的方法应该是什么吗?

提前致谢!

您可以将其包装到组件中的一个函数中:

public _hasErrorClass(): boolean {
  return (this.conditionsForm.get('acceptTerms').touched || this.conditionsForm.get('acceptTerms').dirty)
         && this.conditionsForm.get('acceptTerms').errors;
}

然后在您的模板中使用它:

<div class="form-group has-required" [ngClass]="{'has-error': _hasErrorClass()}"></div>

你可以尝试另外一种方式:Angular OOTB 分配 类 例如 ng-dirty, ng-touched, ng-invalid 来形成控件,你可以设置样式在组件的样式表中。

input.ng-invalid.ng-dirty {
  // style definition here
}

我认为您不需要同时检查脏污和触摸。查看反应式表单文档 - https://angular.io/guide/reactive-forms

<div class="form-group has-required"
    [ngClass]="{'has-error':  conditionsForm.acceptTerms.touched && conditionsForm.acceptTerms.errors}">
</div>

我会选择适用于所有 formControls 的这个:

public hasError(formControlName: string): boolean {
 if (this.user.get(formControlName).errors) {
  return true;
 }
 else {
  return false;
 }
}

HTML代码:

<div [ngClass]="{'has-error': hasError('acceptTerms')}">
// Other HTML
</div>

因此,对于其他表单控件,您可以轻松地将其用作:

<div [ngClass]="{'has-error': hasError('another_formcontrol')}">
 //
</div>

Working_Demo