简体   繁体   English

如何手动取消选中/选中一个primeng复选框

[英]how to uncheck/check a primeng checkbox manually

html html

<p-checkbox name="showLinkedRisksOnly" id="showLinkedRisksOnlyChkBx" 
   label="Show Only Linked Risks" binary="true" (click)="showOnlyLinkedRisks($event)"
   [ngModel]="showLinkedRisksOnly" ></p-checkbox>

typescript打字稿

showOnlyLinkedRisks($event){
  if(condition){
    this.showLinkedRisksOnly = !this.showLinkedRisksOnly;
  }
}

I am trying to change the state of checkbox back to before it was checked/unchecked based on condition.我正在尝试将复选框的状态更改回根据条件选中/取消选中之前的状态。 But for some reason the checkbox and model get out of sync when I do change the value of this.showLinkedRisksOnly.但是由于某种原因,当我更改 this.showLinkedRisksOnly 的值时,复选框和模型会不同步。 Is it possible to achive是否可以达到

First, binding onChange event instead of click event.首先,绑定 onChange 事件而不是 click 事件。 Then add checkbox instance to event然后将复选框实例添加到事件

<p-checkbox name="showLinkedRisksOnly" #something id="showLinkedRisksOnlyChkBx" label="Show Only Linked Risks" binary="true" (click)="showOnlyLinkedRisks($event, something)" [ngModel]="showLinkedRisksOnly"></p-checkbox>

And in typescript在打字稿中

showOnlyLinkedRisks(event, control) {
    if (false) {
      control.checked = false;
    } else { this.showLinkedRisksOnly = event.checked; }
}

Sorry for my bad english!对不起,我的英语不好!

Method 1 - Handle ngModelChange + trigger change detection方法一——处理ngModelChange+触发变化检测

To make the checkbox readonly, you can handle the ngModelChange event:要使复选框只读,您可以处理ngModelChange事件:

<p-checkbox ...
  [ngModel]="showLinkedRisksOnly" 
  (ngModelChange)="showOnlyLinkedRisks($event)">
</p-checkbox>

and follow these steps in the event handler:并在事件处理程序中执行以下步骤:

  1. Set the new value设置新值
  2. If the checkbox is readonly如果复选框是只读的
    1. Trigger change detection触发变化检测
    2. Put the original value back恢复原值
constructor(private cd: ChangeDetectorRef) { }

showOnlyLinkedRisks(value) {
  this.showLinkedRisksOnly = value;    // Set the new value
  if (!this.condition) {               // If the checkbox is readonly
    this.cd.detectChanges();           // Trigger change detection
    this.showLinkedRisksOnly = !value; // Put the original value back
  }
}

See this stackblitz for a demo.有关演示,请参阅此 stackblitz


Method 2 - Two-way binding + disable control方法二——双向绑定+禁用控制

An alternative method is to use two-way binding, and to disable the control to prevent changes:另一种方法是使用双向绑定,并禁用控件以防止更改:

<p-checkbox ...
  [(ngModel)]="showLinkedRisksOnly" 
  [disabled]="!condition">
</p-checkbox>

See this stackblitz for a demo.有关演示,请参阅此 stackblitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM