[Fixed] How do you run a function on the result of NgFor in Angular2?


Consider a list of all of the users in your system:

  allUsers = {
    a: {name:'Adam',email:'[email protected]',level:'admin',group:'Owners'},
    b: {name:'Barbra',email:'[email protected]',level:'admin',group:'Owners'},
    c: {name:'Chris',email:'[email protected]',level:'standard',group:'Managers'},
    d: {name:'Dennis',email:'[email protected]',level:'standard',group:'Managers'},
    e: {name:'Elizabeth',email:'[email protected]',level:'standard',group:'Staff'},
    f: {name:'fred',email:'[email protected]',level:'visitor',group:'Visitor'},


Then a list of the users on a project:

usersList = ['a','b','d','f'];

So you have a nice easy function to take the user id and lookup the rest of the user details:

    console.log('Getting User with Id:', userId);
    if(allUsers[userId]) return allUsers[userId];

Then in the template you use *ngFor to loop through the users in the list, but you want to then lookup the full set of details

<tr *ngFor="#userId in usersList" #user="getUser(userId)">

Doesn’t work…
Without creating custom components or other more complex stuff I can’t figure out how to run the getUser function once per user. I can of course run it over and over like:


but this doesn’t seem like the best way.
Is there an easier way to get access to the userId variable and set it as a local variable?

Here’s a plunker of what I’ve been playing with so far


Though you can create a variable on ngFor template directive, but that variable can only take value of index, even, odd & last.

Thats why I could use pipe for this case, where you need to pass usersList & allUsers to custom @Pipe getUsers (it will act same as a filter in Angular1).


<tr *ngFor="let user of usersList | getUsers: allUsers">


  name: 'getUsers',
  pure: false
export class GetUserPipe implements PipeTransform {
    this.test = 'Test';
  transform(array:Array<string>, object: any) : any {
    // for..in loop
    let output = [];
    for (var num in array)
      // somehow object goes inner side
    return output;

Demo Plunkr

Leave a Reply

(*) Required, Your email will not be published