How to Add a Validator dynamically to a FormControl in Angular 2

后端 未结 1 1050
悲&欢浪女
悲&欢浪女 2021-02-02 00:56

I am using ReactiveFormsModule and have defined all my form controls including simple validators such as Validators.required within a const configuration.

I

1条回答
  •  深忆病人
    2021-02-02 01:19

    Looking at your code, what you could do:

    Please enter a Site, eg. xyz.

    Look at [formControl]="site_id_control"

    Then, this way, you can add or remove the validators from that specific control like this:

    inside your class:

    export class JobSearchEditComponent {
        private site_id_control=this.form.controls['site_id'];
    
        updateValidator(){
           let exisitingValidators = this.site_id_control.validators;
           this.site_id_control.setValidators(Validators.compose([...existingValidators , exampleValidator]))
    
            // you probably also need this : 
             this.site_id_control.updateValueAndValidity();
    
        }
    }
    

    0 讨论(0)
提交回复
热议问题