Example reproduced and resolved at: https://stackblitz.com/edit/angular-ivy-h4wyta?file=src/app/app.component.ts
disabled: this.f.rolling.value === true
Simply this won't work. You have to detect the changes on toggle.
First of all simplify the form initialization.
this.formGroup = this.formBuilder.group({
startDate: new FormControl(this.testObject.startDate, Validators.required),
endDate: new FormControl(this.testObject.endDate, Validators.required),
rolling: this.testObject.rolling
});
And there is two ways to resolve the issue.
- Subscribe to FormControl's valueChanges event.
- Subscribe to MatSlideToggle's OnChange event.
Way 1:
this.formGroup.get("rolling").valueChanges.subscribe(value => {
this.rollingChanged(value);
});
Way 2:
onChange() {
const value = this.formGroup.get("rolling").value;
this.rollingChanged(value);
}
Then you have to do the disable work.
rollingChanged(value: boolean) {
const control = this.formGroup.get("endDate");
if (value) {
control.reset();
control.clearValidators();
control.disable();
} else {
control.enable();
control.setValidators([Validators.required]);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…