Angular2: Find out if FormControl has required validator?

前端 未结 7 767
无人共我
无人共我 2020-12-06 08:50

does someone know a way to find out for an Angular2 FormControl if the required validor is registered for the control.

this.form = builder.group({name: [\'\'         


        
7条回答
  •  無奈伤痛
    2020-12-06 09:38

    While there is no Angular API to directly find if the required validator is set for a particular field, the roundabout way to achieve this is like as below:

    import { NgForm, FormControl } from '@angular/forms';
    
    const isRequiredControl = (formGroup: NgForm, controlName: string): boolean => {
        const { controls } = formGroup
        const control = controls[controlName]
        const { validator } = control
        if (validator) {
            const validation = validator(new FormControl())
            return validation !== null && validation.required === true
        }
        return false
    }
    

    I have tested this and this triggers only if the Validator.Required validator is added to the particular FormControl.

提交回复
热议问题