我有一个PrimeNg的下拉列表,其中包含一些元素。
.ts
this.cities = [
{name: 'New York', code: 'NY'},
{name: 'Rome', code: 'RM'},
{name: 'London', code: 'LDN'},
{name: 'Istanbul', code: 'IST'},
{name: 'Paris', code: 'PRS'}
];
.html
<p-dropdown
[options]="cities"
[(ngModel)]="selectedCity1"
placeholder="Select a City"
optionLabel="name"
[showClear]="true">
<ng-template let-item pTemplate="item" >
<span style="background-color: green">{{item.name}}</span>
</ng-template>
</p-dropdown>
.scss
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.pink {
background-color: pink;
}
我设法使用ng模板为所有元素设置了背景,但我不知道如何从下拉列表中为每个元素制作不同的颜色
链接到代码
在数组中添加styleClass属性:
this.cities = [
{name: 'New York', code: 'NY', styleClass: 'green'},
{name: 'Rome', code: 'RM', styleClass: 'blue'},
{name: 'London', code: 'LDN', styleClass: 'red'},
{name: 'Istanbul', code: 'IST', styleClass: 'yellow'},
{name: 'Paris', code: 'PRS', styleClass: 'pink'}
];
以及在HTML 中
<span [class]="item.styleClass">{{item.name}}</span>