how can I change chips color in Primeng?

2.7k views Asked by At

I want to change color chips in primeng,that whenever I select one I get a diffrent color!, can anyone help me how to do that!

enter image description here

my code :

 <p-multiSelect [options]="cars" [(ngModel)]="selectedCars1"  [selectionLimit]=3 [panelStyle]="{minWidth:'12em'}"
                         [maxSelectedLabels]=2></p-multiSelect>
          <p>Selected Cars: </p>
          <p-chips [(ngModel)]="selectedCars1" ></p-chips>
2

There are 2 answers

5
thisdotutkarsh On

To add a different background to your PrimeNG chips, you can do the following,

  • In your component.html file,
<p-chips [(ngModel)]="selectedCars" (onAdd)="onChipAdd($event)"></p-chips>
  • In your component.ts file,

Create an event handler for the onAdd event along with a function to select all elements in the document with the CSS selector li.p-chips-token. This function essentially helps in accessing all the PrimeNG chips.

Since the requirement specifies that the background of each PrimeNG chip should differ, we would need to also create a function to generates random colors.

onChipAdd(event) {
  console.log(event);
  setTimeout(() => {
    this.modifyBackground(), 0
  });

}

generateBackground() {
  let letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

modifyBackground() {
  let colorOfInterest = this.generateBackground();
  let chipsOfInterest =
    document.querySelectorAll<HTMLElement>('li.p-chips-token');
  console.log(chipsOfInterest);
  if (chipsOfInterest.length > 0) {
    let chipOfInterest = chipsOfInterest[chipsOfInterest.length - 1];
    chipOfInterest.style.backgroundColor = colorOfInterest;
  }
}

TLDR;

For your reference, please find link to a working demo here

Edit:

If your requirement was to only change the background color of the PrimeNG chip from the default background color, please do the following.

In your styles.css file,

.p-chips ul.p-chips-multiple-container .p-chips-token {
  color: #000; 
  background: #dfdfdf !important; /* Add the required background color */
}
0
Yair_May On

Maybe I'm a bit late but I achieve it in the following way and add a Border-Radius

<p-chip [ngStyle]="{'background': '#EF5350','border-radius': '15px' }"></p-chip>