Get validators present in FormGroup/FormControl

前端 未结 5 1768
感动是毒
感动是毒 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条回答
  •  囚心锁ツ
    2020-12-10 11:19

    I adjusted the code from joh04667 and HankCa to this:

    export const hasValidator = (form: FormGroup, controlPath: string, validator: string): boolean => {
      const control = form.get(controlPath);
      const validators = control.validator(control);
      return !!(validators && validators.hasOwnProperty(validator));
    };
    

    Which I store in a file called util.ts and import in the component that contains the form like this:

    import * as util from '@app/shared/util';
    

    And define util in your class:

    public util = util;
    

    Add the directive to your input component like this:

    [required]="util.hasValidator(myForm, 'path.to.control', 'required')"
    

提交回复
热议问题