ngFor每次迭代调用自定义函数

时间:2018-11-07 15:43:10

标签: angular

我想实现这样的东西:

<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>

但是在ngFor循环中调用上述getContact(callLog)会导致模板解析错误。

是否可以为每个ng循环迭代调用自定义函数?或实现我想要的任何好的建议。

非常感谢。

2 个答案:

答案 0 :(得分:1)

您可以在NgForOf内添加另一个模板,例如可以使用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>

在模板中使用函数不是一个好习惯,在每个更改检测周期中,该函数都会被调用两次。

答案 1 :(得分:0)

最好在代码中使用forkJoin创建数组

forkJoin很简单,只需要包含一个“调用”数组即可,例如。

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);
});

一个愚蠢的例子stackblitz