我正在使用 AngularTS 和 primeNG。
下面是我的 html p-checkbox 代码,我还有 rowEdit on row Click 功能以及额外的此代码,因此当我进行编辑模式时,请返回此。
selectDeleteTaskNode code has the selected node but checkbox is not showing checked.[checked == true]
<p-checkbox
*ngIf="i === 0"
[binary]="true"
class="mr-1"
styleClass="edit-checkbox"
[disabled]="!canEdit"
(onChange)="onCheckboxChange($event, rowNode)"
(click)="$event.stopPropagation()"
></p-checkbox>
下面是我上面的 TS 代码
onCheckboxChange(event: any, rowNode: any) {
if (event.checked === true) {
this.selectDeleteTaskNode.push(rowNode.node);
// Update the node selection state
this.nodeSelectionStates[rowNode.node] = event.checked;
} else {
const index = this.selectDeleteTaskNode.indexOf(rowNode.node);
if (index > -1) {
this.selectDeleteTaskNode.splice(index, 1);
this.nodeSelectionStates[rowNode.node] = !event.checked;
}
}
}
如果我可以通过某种条件过滤 [(ngModal)] 值,它将检查节点是否存在于内部
selectDeleteTaskNode or not if yes then p-checkbox's checked ==true else False
要解决此问题,我们可以使用 [checked] 绑定来确保复选框反映该节点是否在 selectDeleteTaskNode 数组中。我们还将修改 onCheckboxChange() 函数以更稳健地处理选择和取消选择
<p-checkbox
*ngIf="i === 0"
[binary]="true"
class="mr-1"
styleClass="edit-checkbox"
[disabled]="!canEdit"
[checked]="isNodeSelected(rowNode.node)" <!-- Bind checked state -->
(onChange)="onCheckboxChange($event, rowNode)"
(click)="$event.stopPropagation()"
></p-checkbox>
// Check if the node is selected by looking in the array
isNodeSelected(node: any): boolean {
return this.selectDeleteTaskNode.includes(node); // Ensure the node's existence in selected array
}
onCheckboxChange(event: any, rowNode: any) {
if (event.checked) {
// Add the node to the selected array if it doesn't already exist
if (!this.selectDeleteTaskNode.includes(rowNode.node)) {
this.selectDeleteTaskNode.push(rowNode.node);
}
} else {
// Remove the node from the selected array if unchecked
const index = this.selectDeleteTaskNode.indexOf(rowNode.node);
if (index > -1) {
this.selectDeleteTaskNode.splice(index, 1);
}
}
// Optionally, keep node selection states updated if needed
this.nodeSelectionStates[rowNode.node] = event.checked;
}