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 */
}