How to use an alias name for Angular expression?

Viewed 5537

I am using Angular 7

I have following template

<div>
{{myService.userInfo.firstName}} {{myService.userInfo.lastName}}
</div>

I want to make it short by substituting user instead of myService.userInfo

<div>
{{user.firstName}} {{user.lastName}}
</div>

How can I do this like ng-init in AngularJS.

3 Answers

create a getter property that will return the userinfo object

 get user(){
      return this.myService.userInfo;
 }

and use like

<div>
   {{user.firstName}} {{user.lastName}}
</div>

If you want to use a custom pipe, you can do something like this

@Pipe({name: 'namePipe'})
export class NamePipe implements PipeTransform {
  transform(value: any, prop: string): string {
     return value.userInfo[prop];
  }
}

<div>
    {{myService | namePipe:'firstName'}} {{myService | namePipe:'lastName'}}
</div>

But at that point you aren't saving any space in your html. You could make two pipes, and reference them like this:

@Pipe({name: 'firstName'})
export class FirstNamePipe implements PipeTransform {
  transform(value: any): string {
     return value.userInfo.firstName;
  }
}

@Pipe({name: 'lastName'})
...

<div>
    {{myService | firstName}} {{myService | lastName}}
</div>

But if this is the only place you are referencing them, then it's not really worth it. You could set a variable let user = this.myService.userInfo but that is ugly and you will have to manually update if there is a change. Maybe you could pass your information into a child component (ask if you want to see an example) and access the fields that way, but with how little code you provided I don't know what is best for your use case. But I don't think there is clean way to achieve what you want besides the other answers given.

Related