skip to Main Content

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


  1. Plenty of ways you can achieve:

    Solution 1: Implement the ternary conditional to display title in the view.

    <ul>
        <li *ngFor="let d of data">
          {{ d.sex == 'Male' ? 'Mr.' : d.sex == 'Female' ? 'Mrs.' : '' }} {{ d.firstname }} {{d.lastname}}
        </li>
    </ul>
    

    Solution 2: Add the title properties in each object for the data array.

    this.data = this.data.map((x) => ({
      ...x,
      title: x.sex == 'Male' ? 'Mr.' : x.sex == 'Female' ? 'Mrs.' : '',
    }));
    
    <ul>
        <li *ngFor="let d of data">
          {{ d.title }} {{ d.firstname }} {{d.lastname}}
        </li>
    </ul>
    

    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.

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'title'
    })
    export class TitlePipe implements PipeTransform {
      transform(value: any, args?: any): any {
        return value == 'Male' ? 'Mr.' : value == 'Female' ? 'Mrs.' : '';
      }
    }
    

    Make sure that you have imported the pipe into the app module before using it.

    <ul>
        <li *ngFor="let d of data">
          {{ d.sex | title }} {{ d.firstname }} {{d.lastname}}
        </li>
    </ul>
    

    Demo @ StackBlitz

    Login or Signup to reply.
  2. 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:

    <ul>
        <li *ngFor="let d of data">
          {{ d.sex === 'Male' ? 'Mr.' : 'Mrs.' }} {{ d.firstname }} {{ d.lastname }}
        </li>
    </ul>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search