Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2: Access property of pipe returning object

I have a custom angular2 pipe, which converts uid's (strings) to UserInfo objects using a service.

@Pipe({name: 'userInfo'})
export class UserInfoPipe implements PipeTransform {

    constructor(public _userService: UserService) {
    }

    transform(uid:string) : any {
        /*let users = this._userService.users.filter((u)=> {
            return u.uid==uid;
        });
        if(users.length==1) return users[0];
        return null;*/

        return {"Name":"hans","Age":13};
    }
} 

And in my component I have a binding:

 <Label row="4"  text="Author: {{event?.author | userInfo | .Name}}" class="small-spacing"></Label>

event?.author returns the UID, and after piping it through userInfo I have an object. But how can I access properties of that object? Is there a syntax for that? .Name doesn't work.

like image 428
Timo Avatar asked Aug 04 '16 15:08

Timo


People also ask

What does .pipe do in Angular?

Use pipes to transform strings, currency amounts, dates, and other data for display. Pipes are simple functions to use in template expressions to accept an input value and return a transformed value. Pipes are useful because you can use them throughout your application, while only declaring each pipe once.

Can we use pipe in component?

It's easy to create custom pipes to use in your templates to modify interpolated values. You don't have to duplicate your code if you want to also use a pipe's functionality in a component class. All you have to do really is inject the pipe like a service, and then call its transform method.


2 Answers

I just found out that

(event?.author | userInfo).Name   

does exactly what I want: It displays the Name property of the object returned by the pipe.

like image 194
Timo Avatar answered Sep 23 '22 05:09

Timo


Not sure if it's the correct way, but I'd pass additional parameter into your pipe.

<Label row="4"  text="Author: {{event?.author | userInfo : {"field": "Name"} }}" class="small-spacing"></Label>

In the pipe I check this parameter and do some special logic:

@Pipe({name: 'userInfo'})
export class UserInfoPipe implements PipeTransform {

  constructor(public _userService: UserService) {
  }

  transform(uid:string, params) : any {
    if (params.field && params.field == 'Name') {

        /*let users = this._userService.users.filter((u)=> {
            return u.uid==uid;
        });
        if(users.length==1) return users[0];
        return null;*/

        return {"Name":"hans","Age":13};
    }
  }
} 
like image 30
Andrei Zhytkevich Avatar answered Sep 22 '22 05:09

Andrei Zhytkevich