I have the following data in Angular:
data = [
{"id": "1", "firstname": "Test", "lastname": "Test2", "sex": "Female"},
{"id": "2", "firstname": "fname", "lastname": "lname", "sex": "Male"},
{"id": "3", "firstname": "Rajesh", "lastname": "Singh", "sex": "Male"},
{"id": "4", "firstname": "Sim", "lastname": "Sen", "sex": "Female"}
]
I want the output as:
Mrs. Test Test2
Mr. fname lastname
Mr. Rajesh Singh
Mrs. Sim Sen
My Code:-
<ul>
<li *ngFor="let d of data">
{{ d.firstname }} {{d.lastname}}
</li>
</ul>
Please tell me how can I convert the gender to Mr and Mrs.
I am new to Angular.
Please help.
2
Answers
Plenty of ways you can achieve:
Solution 1: Implement the ternary conditional to display title in the view.
Solution 2: Add the
title
properties in each object for thedata
array.Solution 3: Implement Angular pipe
You can create an Angular pipe for title by passing the
sex
value. This approach will provide a better performance as Angular pipe will cache the pipe result.Make sure that you have imported the pipe into the app module before using it.
Demo @ StackBlitz
You can achieve this by using Angular’s interpolation
{{ }}
with a conditional (ternary) operator. This operator can be used to render the correct title based on the gender. Here’s how you can modify your code: