Search code examples
angularprimeng

Prevent PrimeNG <p-chip> from being removed on onRemove event but keep the remove icon visible


I’m using the component from PrimeNG in my Angular project, and I want to prevent the chip from being removed when the remove icon is clicked. However, I still want the remove icon to be visible and clickable for custom actions.

Here’s a simplified version of my code:

<p-chip
  label="sed"
  removeIcon="pi pi-download"
  icon="pi pi-microsoft"
  [removable]="true"
  (onRemove)="onRemove($event)"
></p-chip>

In the TypeScript file:

onRemove(event: Event) {
  event.preventDefault(); // I tried this, but it doesn't stop the chip from being removed
  console.log('Remove icon clicked, but chip should remain visible.');
}

Problem: The chip is still being removed from the DOM when the remove icon is clicked, despite my attempts to prevent it in the onRemove method.

Is there any way to stop the chip from being removed while keeping the remove icon functional for other actions?


Solution

  • You can do the following :

    • Read the chip you want to remove using @ViewChild().

    • Inside the onRemove() function reset the chip.visible to true, because in the source code of removable chip they just set the visible to false and emit the onRemove event : Here is the line in source code

    Code: TS:

      @ViewChild('chipToRemove') chip: Chip;
      onRemoveChip() {
        this.chip.visible = true;
        console.log(this.chip);
      }
    

    HTML:

    <div class="p-d-flex p-ai-center">
      <p-chip
        #chipToRemove
        (onRemove)="onRemoveChip()"
        label="sed"
        removeIcon="pi pi-download"
        icon="pi pi-microsoft"
        [removable]="true"
      ></p-chip>
    </div>