【问题标题】:Angular dynamically check and update validatorsAngular 动态检查和更新验证器
【发布时间】:2018-06-09 03:12:55
【问题描述】:

我需要从指令动态地将验证器添加到角度表单控件。

简化:

@Directive({ selector: 'my-directive' })
export class MyDirective implements AfterViewInit  {
  @Input() myDirective: boolean;
  control: AbstractControl;
  constructor(private form: NgForm, private el: ElementRef) {}
  ngAfterViewInit() {
    setTimeout(() => {
      const name = this.el.nativeElement.getAttribute('name');
      this.control = this.form.controls[name];
      // this.control.setValidator... kills my other validators.
    });
  }
}

如何检查此控件是否具有“必需”属性,如果没有则设置它?不覆盖其他验证器?

【问题讨论】:

    标签: angular validation angular-directive


    【解决方案1】:
    if(!this.control.hasError('required') {
       let existingErrors = this.control.errors;
       existingErrors['required'] = {'required': ''};
       this.control.setErrors(existingErrors);
    }
    

    首先检查控件是否已经有所需的错误,如果没有 - 将其添加到现有错误并将更新的错误设置回控件

    【讨论】:

    • 感谢您的回答。但是,请不要发布仅代码的答案,而是尝试解释您解决问题的方法。
    • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    猜你喜欢
    • 1970-01-01
    • 2019-05-07
    • 2017-09-22
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多