Issue
I have an Angular template, like this
<div *ngFor="let hero of heroes">
<p>Name: {{ getHeroAttribute(hero)?.name || '' }}</p>
<p>Skills: {{ getHeroAttribute(hero)?.skills || '' }}</p>
</div>
From the template above, getHeroAttribute()
function will be called multiple times on render. Can I create an attribute on the element parent? So that I can get name
and skills
without multiple calls of getHeroAttribute()
?
Let's assume that I must use this function to get its attribute, I cannot use hero.name
or hero.skills
to show the values.
Solution
In general it's a bad idea use a function in .html because this is called several times.
But you can "minimize" the effect if only call a time and use *ngIf as
<div *ngFor="let hero of heroes">
<ng-content *ngIf="getHeroAttribute(hero) as dataHero">
<p>Name: {{ dataHero?.name || '' }}</p>
<p>Skills: {{ dataHero?.skills || '' }}</p>
</ng-content>
</div>
This approach has the problem in the function not return a value so you can
use, see the || {name:'',skills:''}
<div *ngFor="let hero of heroes">
<ng-content *ngIf="getHeroAttribute(hero) || {name:'',skills:''} as dataHero">
<p>Name: {{ dataHero?.name || '' }}</p>
<p>Skills: {{ dataHero?.skills || '' }}</p>
</ng-content>
</div>
or
<div *ngFor="let hero of heroes">
<ng-content *ngIf="{data:getHeroAttribute(hero)} as dataHero">
<p>Name: {{ dataHero.data?.name || '' }}</p>
<p>Skills: {{ dataHero.data?.skills || '' }}</p>
</ng-content>
</div>
But really the best bet is "extends" our heroes array
//after you get the heroes
this heroesExtends=this.heroes.map(x=>({...x,data:getHeroAttribute(x)})
//use heroesExtends
<div *ngFor="let hero of heroesExtends">
<p>Name: {{ hero.data?.name || '' }}</p>
<p>Skills: {{ hero.data?.skills || '' }}</p>
</ng-content>
</div>
Answered By - Eliseo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.