<p-checkbox name="showLinkedRisksOnly" id="showLinkedRisksOnlyChkBx"
label="Show Only Linked Risks" binary="true" (click)="showOnlyLinkedRisks($event)"
[ngModel]="showLinkedRisksOnly" ></p-checkbox>
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. Is it possible to achive
First, binding onChange event instead of click event. 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!
To make the checkbox readonly, you can handle the ngModelChange
event:
<p-checkbox ...
[ngModel]="showLinkedRisksOnly"
(ngModelChange)="showOnlyLinkedRisks($event)">
</p-checkbox>
and follow these steps in the event handler:
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.