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

后端 未结 1 1049
悲&欢浪女
悲&欢浪女 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:

    <div class="form-group" [ngClass]="{'has-danger':!form.get('site_id').valid}">
            <label for="site_id" class="form-control-label">Site</label>
            <input id="site_id" [formControl]="site_id_control" type="text" placeholder="Site" class="form-control input-sm">
            <div *ngIf="!form.get('site_id').valid">
                <div class="form-control-feedback">Site is required?</div>
                <small class="form-text text-muted">Please enter a Site, eg. xyz.</small>
            </div>
        </div>
    

    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)
提交回复
热议问题