I am trying to set the whole fromGroup
to invalid with a custom validator, which doesn't seems to work...
The goal of the code bellow is to compare two instance of a fromGroup.
- If they matched it means no changes has been made so it has to be invalid.
- Else it doesn't match it means changes has been made so it has to be valid.
My variable isValid
works correctly when I logged it. It turns to true or false depending on changes.
But I cannot manage to make the from invalid, I've tried many ways form articles and stack-overflow, which has a stackblitz whichi doesn't seems to work neither.
Like this.updateCyclistForm.setErrors({ 'invalid': true});
from Angular 6 Required only one field from many fields Reactive Form
I've seen many similar posts has this one which use controls which is not the case here.
public updateCyclistForm: FormGroup
public savedStateOfForm: FormGroup
...
constructor(...) {
...
this.savedStateOfForm = new FormGroup({
status: new FormControl(this.currentReg.status, []),
role: new FormControl(this.currentReg.role, []),
passes: new FormControl({ data: this.passesUID }, [])
})
this.updateCyclistForm = new FormGroup({
status: new FormControl(this.currentReg.status, []),
role: new FormControl(this.currentReg.role, []),
passes: new FormControl({ data: this.passesUID }, [])
})
this.updateCyclistForm.setValidators(this.isValid(this.savedStateOfForm));
}
...
isValid = (clone: FormGroup): ValidatorFn => {
return (group: FormGroup): ValidationErrors => {
let isValid = JSON.stringify(clone.value) != JSON.stringify(control.value)
group.setErrors({ 'valid': isValid });
this.updateCyclistForm.setErrors({ 'valid': isValid });
return
}
}
HTML
<button type="submit" [disabled]="!updateCyclistForm.valid">Save</button>
The button is never disabled, why ? What am I doing the wrong way ?
EDIT :
I've also tried to use something similar as @Adam's answer. Which make my button
disabled for life.
isValid = (clone: FormGroup): ValidatorFn => {
return (group: FormGroup) : ValidationErrors => {
return {
invalid: JSON.stringify(clone.value) != JSON.stringify(group.value) ? true : null
}
}
}