On change of checkbox state remain same in UI

那年仲夏 提交于 2020-01-06 01:19:04

问题


<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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!