更改复选框状态后,UI中的状态保持不变 [英] On change of checkbox state remain same in UI
问题描述
<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.
推荐答案
问题显示在此堆叠闪电战。取消选中该复选框后,在代码中该值设置为 true
,但该复选框仍未被选中。
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:
- 强制通过调用
ChangeDetectorRef.detectChanges
- 立即更改检测将值设置为
true
- 让更改检测机制更新复选框以反映更新后的值
在下面的代码中,我处理了 ngModelChange
事件。问题中提到的条件行为是使用 keepChecked
属性进行仿真的:
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;
}
}
请参见此堆叠闪电战进行了演示。
可以通过在 setTimeout
回调中异步设置值来获得类似的结果:
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;
});
}
}
但我更喜欢通过调用 ChangeDetectorRef.detectChanges
。
这篇关于更改复选框状态后,UI中的状态保持不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!