【问题标题】:Apply Angular validation class to non-FormControl parent将 Angular 验证类应用于非 FormControl 父级
【发布时间】:2017-10-22 16:07:19
【问题描述】:

我有一个响应式表单,其中每个控件都遵循这个基本结构:

<div class="form-group">
    <label for="vtype">Vehicle Type</label>
    <input formControlName="vtype" class="form-control" placeholder="Type"/>
</div>

Angular 会自动为每个 FormControl 和 FormGroup 添加验证类,例如 ng-valid、ng-touched、ng-dirty 等。

出于样式目的,我还想将这些相同的类应用于控件的父 div 元素。例如:

<div class="form-group ng-dirty ng-touched ng-invalid">
    <label for="vtype">Vehicle Type</label>
    <input formControlName="vtype" class="form-control ng-dirty ng-touched ng-invalid" placeholder="Type"/>
</div>

我还没有找到使用 Angular 执行此操作的本地方法。我试图创建一个指令,将父 div 的类与控件的验证类同步,但我无法处理 touch 事件以在父元素上设置 ng-touched/ng-untouched 类。

任何帮助将不胜感激!

【问题讨论】:

  • touched 标志设置为对简单的blur 事件的响应。您可以通过这种方式重现它。

标签: angular angular2-forms


【解决方案1】:
<div class="form-group ng-dirty ng-touched ng-invalid" [class.ng-invalid]="myForm.vtype.invalid">
    <label for="vtype">Vehicle Type</label>
    <input formControlName="vtype" class="form-control ng-dirty ng-touched ng-invalid" placeholder="Type"/>
</div>

这有助于您应用动态类。

【讨论】:

    【解决方案2】:

    我知道这是一个老问题,但答案可能很有用。

    创建自定义指令并使用 HostBinding:

    import { ContentChild, Directive, ElementRef, HostBinding } from '@angular/core';
    import { FormControlName } from '@angular/forms';
    
    @Directive({
        selector: 'div.form-group'
    })
    export class ParentElementValidatorDirective {
        @ContentChild(FormControlName) controlName: FormControlName;
        @HostBinding('class.ng-invalid') get invalid() { return this.controlName.invalid && this.controlName.touched; }
        @HostBinding('class.ng-valid') get valid() { return this.controlName.valid && this.controlName.touched; }
        constructor(element: ElementRef) { }
    }
    

    注意指令的选择器!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 2021-11-16
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 2018-03-28
      相关资源
      最近更新 更多