Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5: Validating disabled fields

I found this post but it cant solve my problem. I can't validate a simple form with FormControls disabled. I did make a stackblitz example here, please check out my code and verify that is impossible to verify the value of the name control if it's disabled.

Stackblitz code

Thank you in advance.

like image 660
Ricky Avatar asked Feb 04 '19 19:02

Ricky


People also ask

What is the use of abstractcontrol in angular?

It provides some of the shared behavior that all controls and groups of controls have, like running validators, calculating status, and resetting state. It also defines the properties that are shared between all sub-classes, like value , valid , and dirty . It shouldn't be instantiated directly.

What is markAsDirty?

markAsDirty() is to mark all controls as dirty in the form.

What is markAsTouched?

Recalculates the value and validation status of the control. markAsTouched() Marks the control as touched. A control is touched by focus and blur events that do not change the value.


2 Answers

Solution by @Eliseo:

If you want not loose the validate you can use [attr.disabled]="condition ? true : null" (or any condition). This give your control an apparence of disabled but still is "validating".

like image 69
Ricky Avatar answered Oct 29 '22 03:10

Ricky


The reason disabled fields are not validated is because angular forms skips them from the validation. Since the control level is skipped, you will need to add that validation on the group level. credit goes to this comment https://github.com/angular/angular/issues/25182#issuecomment-408629027

The code would look like this:

this.formGroup.setValidators((form) => Validators.required(form.get('disabledControl'));
like image 4
Rstar37 Avatar answered Oct 29 '22 04:10

Rstar37