javascriptangularprimengp-dropdown

Change the colour of p-dropdown items based on a Boolean value


I want to change the background colour of my primeng drop-down items which is dependent on a boolean value that I'm getting from an api and pushing it into a array i.e users

I have a array of objects users which contains 3 fields. Response of the api is:

users=[{user_name:john.doe,user_id:'J012', is_promoted:true},{user_name:jane.doe,user_id:'J013', is_promoted:false}]
So I was trying to map the users array to get the is_promoted
users.map(u=>u.is_promoted);

If is_promoted is true then the background colour of p-dropdown-items must change to a certain colour.I'm not able to achieve this. Should I try [styleClass]? CSS:

:host ::ng-deep.p-dropdown-items{
background:darkgrey
}

HTML

<p-dropdown [options]=users optionlabel="user_name" optionvalue="user_id" 
[ngStyle]="{'highlight':users.is_promoted==true}"[(ngModel)]="selectedValue> //Gives an error

I'm able to select the value here. But I need to change the background colour of the dropdown element based on the boolean value. How to approach this?


Solution

  • You are talking NgPrime dropdown, right?

    You need to use template for this. From the docs:

    .promoted {
       background-color: red;
    
    }
    :host ::ng-deep .p-dropdown-panel .p-dropdown-items .p-dropdown-item {
      padding:0;
    }
    .userItem {
      padding: 0.75rem 1.25rem;
    }
    
    <p-dropdown [options]="users" [(ngModel)]="selectedValue" optionLabel="user_name" optionValue="user_id" >
        <ng-template let-user pTemplate="item">
            <div class='userItem' [class.promoted]="user.is_promoted" >{{user.user_name}}</div>
        </ng-template>
    </p-dropdown>
    

    You need also change padding on .p-dropdown-item because background will be only around the text, not whole option element.