rodent_la
rodent_la

Reputation: 1395

ngFor call custom function for each iteration

I want to implement something like this:

<div *ngFor="let callLog of callLogs; trackBy: trackByFn; let contact = getContact(callLog.user-id);" class="call-log-item">
     ...
     <div> {{ contact ? contact.name : callLog.cache-name }}
     <div> {{ contact ? contact.avatar-url : callLog.avatar-url }}
     ... 
</div>

But calling the above getContact(callLog) in ngFor loop cause template parse error.

Is it possible to call custom function for each ng loop iteration? Or any good suggestion to achieve what i want.

Thanks a lot.

Upvotes: 0

Views: 556

Answers (2)

Eliseo
Eliseo

Reputation: 57939

it's better use forkJoin in code to create an array

forkJoin is easy, just must have an array of "calls",e.g.

import { forkJoin, } from 'rxjs';

//Create an array of Observables, I use map
let myCalls=callLogs.map(x=>this.getContact(x.user-id))
forkJoin(myCall).subscribe(res=>{
    //here you have an array with the result of all your calls
    this.list=res;
    console.log(this.list);
});

A silly example stackblitz

Upvotes: 0

ibenjelloun
ibenjelloun

Reputation: 7733

You can add another template inside the NgForOf, for example you could use an NgIf :

<div *ngFor="let callLog of callLogs; trackBy: trackByFn" class="call-log-item">
    <ng-container *ngIf="getContact(callLog.user-id) as contact"
     ...
     <div> {{ contact ? contact.name : callLog.cache-name }}
     <div> {{ contact ? contact.avatar-url : callLog.avatar-url }}
     ... 
    <ng-container>
</div>

Using functions inside the templates isn't a good practice, the function would be called a couple of times in each change detection cycle.

Upvotes: 1

Related Questions