In Angular, how to add Validator to FormControl after control is created?

后端 未结 5 1703
清酒与你
清酒与你 2020-11-30 23:10

We have a component that has a dynamically built form. The code to add a control with validators might look like this:

var c = new FormControl(\'\', Validato         


        
5条回答
  •  清歌不尽
    2020-11-30 23:56

    To add onto what @Delosdos has posted.

    Set a validator for a control in the FormGroup: this.myForm.controls['controlName'].setValidators([Validators.required])

    Remove the validator from the control in the FormGroup: this.myForm.controls['controlName'].clearValidators()

    Update the FormGroup once you have run either of the above lines. this.myForm.controls['controlName'].updateValueAndValidity()

    This is an amazing way to programmatically set your form validation.

提交回复
热议问题