Steff
Steff

Reputation: 43

p-checkbox does not maintaining it's Checked value if I clicked on another component and come back

I am using Angular with TypeScript with primeNG.
Below is my code for HTML p-checkbox, as well I have the rowEdit on row Click feature with extra this code, so when I am doing edit modal and come back this this.

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>

below is my TS code for the above

  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;
      }
    }
  }

if I can filter that [(ngModal)] value by some condition it will check whether the node is present inside

selectDeleteTaskNode or not if yes then p-checkbox's checked ==true else False

Upvotes: 0

Views: 60

Answers (1)

Ronak Koladiya
Ronak Koladiya

Reputation: 1

To fix this, we can use the [checked] binding to ensure the checkbox reflects whether the node is in your selectDeleteTaskNode array. We'll also modify the onCheckboxChange() function to handle selection and deselection more robustly

    <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;
}

Upvotes: 0

Related Questions