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

查看:52
本文介绍了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属性更改时,如何修改MyRequiredValidator以触发验证?

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.

柱塞: 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;
  }
}

请参阅以下代码: https://plnkr.co/edit/14jDdUj1rdzAaLEBaB9G?p=preview .

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

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