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
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With