Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5: set formControl validation state as valid manually

Tags:

angular

I don't know if it is my code or default behaviour. Anyway, I have a control with validity set to a date that is today or in the past. It does work well. My problem is for specific cases, the element can be populated from ngOnInit with an acceptable format. Yet, the form still insists it is invalid. I have to go to the control and manually enter the date that was generated by the system.

What do I have to do?

I did try to set it as valid using:

  this.form.controls['date'].setErrors(null)

However, its value becomes null (instead of just the errors) and I still have to write the date myself to pass it.

like image 416
Nie Selam Avatar asked Jan 10 '18 18:01

Nie Selam


2 Answers

You can do this: this.form.get('date').setErrors(null)

.get('date') will get you the full FormControl

like image 195
Nadhir Falta Avatar answered Nov 15 '22 08:11

Nadhir Falta


this.form.get('date').setErrors(null) works pretty well or ur can simply return an object { dateError: true }.

But beaware that if u need two or more formControl values in your custom validator, you have to put the validator initialization in formGroup , not in formControl.

private setFormgroup(){
   this.myFormGroup = this.formbuilder.group({
          name: [name, { validators: Validators.required }],
          price: [price, { validators: [singleValueCustomValidator] }],

          { validators: this.multiValueCustomValidator });
  }

See this article for full example. https://medium.com/@monir.khan.developer/angular-10-custom-form-validation-example-reactive-forms-3f5432a21fff

like image 42
Monir Khan Avatar answered Nov 15 '22 08:11

Monir Khan