Angular 2 中的条件要求验证器指令 [英] Conditional required validator directive in Angular 2

查看:21
本文介绍了Angular 2 中的条件要求验证器指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据其他字段的值来确定某些表单字段是否为必填字段.内置的 RequiredValidator 指令似乎没有支持这一点,所以我创建了自己的指令:

I need to make certain form fields required or not based on the value of other fields. The built-in RequiredValidator directive doesn't seem to support this, so I created my own directive:

@Directive({
  selector: '[myRequired][ngControl]',
  providers: [new Provider(NG_VALIDATORS, { useExisting: forwardRef(() => MyRequiredValidator), multi: true })]
})
class MyRequiredValidator {
  @Input('myRequired') required: boolean;

  validate(control: AbstractControl): { [key: string]: any } {
    return this.required && !control.value
      ? { myRequired: true }
      : null;
  }
}

示例用法:

<form>
  <p><label><input type="checkbox" [(ngModel)]="isNameRequired"> Is Name Required?</label></p>
  <p><label>Name: <input type="text" [myRequired]="isNameRequired" #nameControl="ngForm" ngControl="name" [(ngModel)]="name"></label></p>
  <p *ngIf="nameControl.control?.hasError('myRequired')">This field is required.</p>
</form>

如果用户首先切换复选框,然后在文本框中键入或擦除文本,这将正常工作.但是,如果用户在文本框为空时切换复选框,则验证消息不会适当更新.

This works fine if the user first toggles the check box and then types or erases text in the text box. However, if the user toggles the check box while the text box is blank, then the validation message doesn't update appropriately.

如何修改 MyRequiredValidator 以在其 required 属性更改时触发验证?

How can I modify MyRequiredValidator to trigger validation when its required property is changed?

注意:我正在寻找一种仅涉及对 MyRequiredValidator 进行更改的解决方案.我想避免向 App 组件添加任何逻辑.

Note: I'm looking for a solution that only involves changes to MyRequiredValidator. I want to avoid adding any logic to the App component.

Plunker:https://plnkr.co/edit/ExBdzh6nVHrcm51rQ5Fi?p=preview

推荐答案

我会使用类似的东西:

@Directive({
  selector: '[myRequired][ngControl]',
  providers: [new Provider(NG_VALIDATORS, { useExisting: forwardRef(() => MyRequiredValidator), multi: true })]
})
class MyRequiredValidator {
  @Input('myRequired') required: boolean;

  ngOnChanges() {
    // Called when required is updated
    if (this.control) {
      this.control.updateValueAndValidity();
    }
  }

  validate(control: AbstractControl): { [key: string]: any } {
    this.control = control;
    return this.required && !control.value
      ? { myRequired: true }
      : null;
  }
}

查看此 plunkr:https://plnkr.co/edit/14jDdUj1rdzAaLEBaB9G?p=preview.

See this plunkr: https://plnkr.co/edit/14jDdUj1rdzAaLEBaB9G?p=preview.

这篇关于Angular 2 中的条件要求验证器指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆