Angular2: Find out if FormControl has required validator?

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

    I don't know what's the exact way is to check if control has required validator or not.

    But workaround could be this, Whenever control has required validator, it adds validator() function to that control.

    eg.

    
    
    constructor(private formBuilder: FormBuilder){
        this.registerForm = this.formBuilder.group({
            firstname: ['', Validators.required]     //<<<===one required validation on firstname control
        });
    
        console.log(this.registerForm.controls.firstname.validator.length);
                                                     //<<<===this will return 1.
       });
    

    }

    In above code, length of validator is one(1)


      console.log(this.registerForm.controls.firstname.validator.length);
                                                     //this will return exception
    

    this line will return one. If no validator is attached then firstname will not have validator() function so in that case I'll give an exception.

    DEMO : https://plnkr.co/edit/I7b5JNAavmCJ6Py1eQRr?p=preview

提交回复
热议问题