Reputation: 3854
I have this div
<div *ngFor="let user of userList">
<div>{{ Name }} </div>
</div>
and i have this object
[
{
"code": "A",
"color": "#0071e3"
},
{
"code": "B",
"name": "#ff0000"
},
{
"code": "C",
"name": "#249309"
},
..
]
if Name starts with `A' i have to give same color that is in given object same in the case with other alphabets
Upvotes: 0
Views: 468
Reputation: 975
In your .html :
<div *ngFor="let user of userList">
<div [style.color]="user.Name | firstLetterBg">{{ user.Name }}</div>
</div>
In your pipe :
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'firstLetterBg'
})
export class FirstLetterBgPipe implements PipeTransform {
private colors: Array<{code: string, color: string}> = [
{
"code": "A",
"color": "#0071e3"
},
{
"code": "B",
"color": "#ff0000"
},
{
"code": "C",
"color": "#249309"
}
];
transform(name: string): string {
const firstLetter = name[0].toUpperCase();
const colorObject = colors.find(x => x.code === firstLetter);
return colorObject ? colorObject.color : '';
}
}
But yes according to @MatthieuRiegler, its better to use a directive. You can re use my code to do that.
Regards,
Upvotes: 1