Conditional required validator directive in Angular 2

耗尽温柔 提交于 2019-12-07 12:41:29

问题


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;
  }
}

Sample usage:

<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.

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

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


回答1:


I would use something like that:

@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;
  }
}

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



来源:https://stackoverflow.com/questions/36986375/conditional-required-validator-directive-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!