Angular2: Find out if FormControl has required validator?

前端 未结 7 754
无人共我
无人共我 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:48

    This function should work for FormGroups and FormControls

      export const hasRequiredField = (abstractControl: AbstractControl): boolean => {
        if (abstractControl.validator) {
            const validator = abstractControl.validator({}as AbstractControl);
            if (validator && validator.required) {
                return true;
            }
        }
        if (abstractControl['controls']) {
            for (const controlName in abstractControl['controls']) {
                if (abstractControl['controls'][controlName]) {
                    if (hasRequiredField(abstractControl['controls'][controlName])) {
                        return true;
                    }
                }
            }
        }
        return false;
    };
    
    0 讨论(0)
提交回复
热议问题