'Mat checkbox not being checked when manually setting it to true inside a method
I am using mat checkbox & want the checkbox to remain checked even if the user clicks on it provided some condition is met. However I can't seem to get it to work. Seems like I'm missing some detail. Thanks in advance for your help.
Here is my html:
<mat-checkbox (change)="isValidState($event)" [(ngModel)]="checkboxState">Admin</mat-checkbox>
The method that I'm calling on change:
isValidState(event: any): void {
if(some condition)
{
this.checkboxState = true;
}
}
Solution 1:[1]
I'm not sure what you want to achieve, but you shouldn't be doing it in (change) output. The reason why it's not working is that, because when you click the checkbox, first it's going through your isValidState() method, and then it's changing the value of the checkbox itself.
You can wrap it like that:
setTimeout(() => {
this.checkboxState = false;
})
But this is not a good way of handling things in angular.
The thing I like to do, is to use reactive forms. I will give you a code example how it would look for your checkbox:
export class AppComponent {
someCondition = true;
myCheckBox = new FormControl();
ngOnInit(): void {
this.myCheckBox.valueChanges.subscribe(value => {
if(this.someCondition) {
this.myCheckBox.setValue(false, {emitEvent: false})
}
})
}
}
and html:
<mat-checkbox [formControl]="myCheckBox">Admin</mat-checkbox>
For me, it makes it easier to control your forms, and all the projects I have been working with were also using this approach.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Panda-313 |
