How to add custom validation after initializing control in angular 4 reactive form?

I am working on an angular 4 application and using reactive forms.

In one of my forms, I need to add a custom check to control after its initialization when checking a checkbox and delete it when unchecking.

THE CODE

form.component.ts

   form : FormGroup;
    constructor( private formGroup : FormBuilder){}
    ngOnInit() {
       this.form = this.formGroup.group({ 
          name : ["", [Validators.required, this.textValidation]]
       });
    }

    public textValidation(control:FormControl)  
    {    
      if(control.value && (control.value).replace(/\s/g, "").length < 1)    
      {      
         return {'stringCheck': true};    
      }    
      return '';  
    }

    addValidation(isChecked)
    {
       if(isChecked){  this.form.controls['name'].setValidators([Validators.required,this.textValidation]);
       }else{
         this.form.controls['name'].clearValidators();
       } 
        this.form.controls['name'].updateValueAndValidity();
    }

form.component.html

<form [formGroup]="form" (ngSubmit)="submitForm()">
   <input type="checkbox" (change)="addValidation($event.target.checked)">
   <div>
      <label>Name</label>
      <imput type="text formControlName="name">
      <small *ngIf="(form.controls['name'].hasError('required') || form.controls['name'].hasError('stringCheck')>Error</small>
   </div>

</form>

Getting this error.

/home/iron/Desktop/BK-admin/bookingkoala_admin/src/app/Industries/AddFrequency/AddFrequency.component.ts(242,79): '(((control: AbstractControl) = > ValidationErrors) | ((control: FormControl) = > "| {'stringChec...' " ValidatorFn | ValidatorFn []. Type '(((control: AbstractControl) = > ValidationErrors) | ((control: FormControl) = > "| {'stringChec...' 'ValidatorFn [].     Type '((control: AbstractControl) = > ValidationErrors) | ((control: FormControl) = > " "| {'stringCheck...' " ValidatorFn ".       Type '(control: FormControl) = > " "| {'stringCheck': boolean; } ' " ValidatorFn ".          "" "| {'stringCheck': boolean; } ' "ValidationErrors".            '' "' ' ValidationErrors '.

- , , .

+4
1

:

  addValidation(isChecked)
    {
       if(isChecked){  this.form.controls['name'].setValidators([Validators.required,this.textValidation]);
       }else{
         this.form.controls['name'].clearValidators();
       } 
        this.form.controls['name'].updateValueAndValidity();
    }

:

 public textValidation(control:FormControl)  
    {    
      if(control.value && (control.value).replace(/\s/g, "").length < 1)    
      {      
         return {'stringCheck': true};    
      }    
      return '';  
    }

validationError.

, :

 if(isChecked){  this.form.controls['name'].setValidators([Validators.required,this.textValidation]);

, , , , .

0

Source: https://habr.com/ru/post/1689957/


All Articles