问题
<input type="checkbox" [(ngModel)]="rowData.is_permitted" (change)="changeStatus()">
changeStatus() {
rowData.is_permitted = true;
}
If I uncheck checkbox but conditionally I want to select the checkbox, the flag updated but not affect in UI.
回答1:
The problem is shown in this stackblitz. After unchecking the checkbox, the value is set to true
in code but the checkbox remains unchecked.
You can do the following to override the action of the user with a change in code:
- Force an immediate change detection by calling
ChangeDetectorRef.detectChanges
- Set the value to
true
- Let the change detection mecanism update the checkbox to reflect the updated value
In the code below, I handle the ngModelChange
event. The conditional behavior mentioned in the question is simulated with the keepChecked
property:
<input type="checkbox"
[(ngModel)]="rowData.is_permitted"
(ngModelChange)="changeStatus()">
changeStatus() {
if (this.keepChecked) {
this.changeDetectorRef.detectChanges();
this.rowData.is_permitted = true;
}
}
See this stackblitz for a demo.
A similar result could be obtained by setting the value asynchronously in a setTimeout
callback:
changeStatus() {
if (this.keepChecked) {
setTimeout(() => {
this.rowData.is_permitted = true;
});
}
}
but I prefer to keep the code synchronous by calling ChangeDetectorRef.detectChanges
.
回答2:
If I understand your question, After changing the input, it remains true.
So, when rowData.is_permitted
is true, you need to make it false.
rowData.is_permitted
is false, you need to make it true.
If this is your problem, try do it by changing changeStatus
function:
rowData.is_permitted = !rowData.is_permitted;
rowData.is_permitted will get the opposite value.
Working example that I forked from @SunilSingh is here
回答3:
You have to change ngModel value on click. May be rowData.is_permitted
default value is true
so, on click it is not changed by your function.
Your changeStatus function will be
changeStatus() {
rowData.is_permitted = !rowData.is_permitted;
}
来源:https://stackoverflow.com/questions/53349706/on-change-of-checkbox-state-remain-same-in-ui