Search code examples
cssangularprimeng

How to change primeNG select button color dynamically according to the option selected by the user


I'm using the p-selectButton from PrimeNG and I would like to know if it's possible to change the color of the button according to the option selected by the user. For example:

enter image description here

If user selects "Off" button turns red and if user selects "On", button turns green. The class that I need to change color is called "p-highlight". The problem is I don't know how to access this class because it seems the tag <p-selectButton> creates a div with p-highlight class, so I don't think it's possible to use [styleClass] or [ngClass] here.

enter image description here

Anyway to change this css class when user selects an option?


Solution

  • It's possible by overriding the css classes, it's not ideal since ng-deep is depricated ( for many years already but it still works )

    ::ng-deep {
          div[aria-labelledby='Off'].p-highlight {
            background: red;
          }
        
          div[aria-labelledby='On'].p-highlight {
            background: green;
          }
        }
    

    An improvement would be to add a class/id to your component and then wrap this CSS due to how ng-deep works (see the StackBlitz code for an example).

    stackblitz

    enter image description hereenter image description here