I'm new in angular and don't know much about it yet. I am showing a list of people in my angular app. And I want to show first letters of their first name and last name as DP if no picture found for that person. My code looks like below:
<div class="people" *ngFor="let user of users">
<div class="s-profile-icon">
<img src={{user.picture}} alt="Profile" />
</div>
<div class="s-name">
{{user.full_name}}
</div>
</div>
Well I know I can use *ngIf
on user.picture
to check if picture is empty? But I don't know how to get first letters of name. For example:
if user.full_name
contains Mary Johnson name and user.picture
is empty then in place of picture, it should show MJ in place of picture. I can design the circle to show letters, just wanted to know how can I get first letters inside loop. Please help me
You can create a method
in your component or create custom angular pipe
for this
create a method to get short name
getShortName(fullName) {
return fullName.split(' ').map(n => n[0]).join('');
}
template
<div class="people" *ngFor="let user of users">
<div class="s-profile-icon">
<img src={{user.picture}} alt="{{getShortName(user.full_name)}}" />
</div>
<div class="s-name">
{{getShortName(user.full_name)}}
</div>
</div>
Updated 🔥
the answer above is consider a bad practices because the method will run in every change detection cycle so the best approch is to create a pipe to get the short name
shortName.pipe.ts
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "shortName"
})
export class ShortNamePipe implements PipeTransform {
transform(fullName: string): any {
return fullName
.split(" ")
.map(n => n[0])
.join("");
}
}
template
{{'My Name' | shortName}}
demo 🚀
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With