Get validators present in FormGroup/FormControl

前端 未结 5 1786
感动是毒
感动是毒 2020-12-10 11:03

I\'m using Material 2 in my app, but in this question I want to solve a problem specifically with Input.

As you can see in API Reference there\'s a

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 11:28

    There is no straight forward or clean way of doing this. Here is the cleanest method that I came across that works. Tested with the latest version of Angular v10.2.0 (as of today)

    Import these

    import {AbstractControl, FormControl, Validators} from '@angular/forms';
    

    Define your control

    anyCtrl = new FormControl('', [Validators.required]);
    

    Add this method

      public hasRequiredField = (abstractControl: AbstractControl): boolean => {
        if (abstractControl.validator) {
          const validator = abstractControl.validator({}as AbstractControl);
          if (validator && validator.required) {
            return true;
          }
        }
        return false;
      }
    

    How to call this method from the HTML

    
    

    Calling it from the Typescript file (logic) within the constructor or ngOnInit

    constructor() {
      console.log(this.hasRequiredField(this.anyCtrl)); // true, false if Validators array does not contain Validators.required
    }
    

提交回复
热议问题