Angular 4 remove required validator conditionally

后端 未结 10 1901
[愿得一人]
[愿得一人] 2021-02-01 01:26

In Angular 4 app I have a form model like this:

this.form = this._fb.group({
    title: [\'\', [Validators.required, Validators.minLength(3), Validators.maxLengt         


        
相关标签:
10条回答
  • 2021-02-01 02:13

    Use empty array to remove all existing validators.

    this.frmFeasibility.controls['pop_name'].setValidators([]);
    this.frmFeasibility.controls['pop_name'].updateValueAndValidity();
    
    0 讨论(0)
  • 2021-02-01 02:21

    if you want to add validation try this one.

    saveDraft() {
       this.form.get('title').setValidators([Validators.required, Validators.minLength(3)]);
       this.form.get('title').updateValueAndValidity();
    }
    

    if you want to remove validators try this one.

    saveDraft() {
     this.form.get('title').clearValidators();
     this.form.get('title').updateValueAndValidity();
    }
    
    0 讨论(0)
  • 2021-02-01 02:23

    To Add Validators:

    this.form = this._fb.group({
        title: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]],
        description: ['', [Validators.required, Validators.minLength(3)]]
    });
    

    or

    this.form.get('title').setValidators([Validators.required,Validators.minLength(3), Validators.maxLength(50)]);

    To Remove the 'Required' validator only, you can reset the validators.

    saveDraft() {
         this.form.get('title').setValidators([Validators.minLength(3), Validators.maxLength(50)]);
         this.form.get('title').updateValueAndValidity();
    }
    

    updateValueAndValidity determines how the control propagates changes and emits events when the value and validators are changed

    0 讨论(0)
  • 2021-02-01 02:28
    saveDraft() {
       this.form.get('title').setValidators([Validators.required, Validators.minLength(3)]);
       this.form.get('title').updateValueAndValidity();
    }
    
    saveDraft() {
     this.form.get('title').clearValidators();
     this.form.get('title').updateValueAndValidity();
    }
    
    0 讨论(0)
提交回复
热议问题