Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactive form valid property return false when form is disabled

I have this simple form and used in create and update cases so for create case the user will enter the data and base on validatorsI will get the form.valid (true,false). In update case I just get the data from api and set this value to the form and make the form disable;

this.form = fb.group({
  name: ['', Validators.required],
  lastName: ['', Validators.required],
  address: [''],
});

so when I make the form disabled the valid value always is false;

 ngOnInit() {
    this.form.patchValue({
      name: 'name',
      lastName: 'Last Name'
    });

    this.form.disable();
  }

stackblitz example

like image 831
Muhammed Albarmavi Avatar asked Jul 22 '18 15:07

Muhammed Albarmavi


People also ask

Is Reactive forms are mutable?

Reactive forms use an explicit and immutable approach to managing the state of a form at a given point in time. Each change to the form state returns a new state, which maintains the integrity of the model between changes.


2 Answers

This is correct. The documentation says:

A control is valid when its status is VALID.

And the documentation of status says:

The validation status of the control. There are four possible validation status values:

  • VALID: This control has passed all validation checks.
  • INVALID: This control has failed at least one validation check.
  • PENDING: This control is in the midst of conducting a validation check.
  • DISABLED: This control is exempt from validation checks.

Your form is disabled, so it is not valid.

like image 149
JB Nizet Avatar answered Sep 23 '22 11:09

JB Nizet


Valid will return false if the form is disabled so I found two way to work around this

instand of check the valid property directly I make a function for checking the validity

 isFormValid() : boolean { 
    return this.form.disabled ? true : this.form.valid
  }

template

<button [disabled]="!isFormValid()" (click)="update()">Update</button>

another way without create isFormValid function

<button [disabled]="!form.valid && form.disabled === false" (click)="update()">Update</button>
like image 26
Muhammed Albarmavi Avatar answered Sep 22 '22 11:09

Muhammed Albarmavi