reduce same function call inside ngFor loop

39 views Asked by At

inside the ngFor loop, there are 3 same function call - processStatus(status). Is there a way to call it only once inside the for loop by saving it in a parameter , and then refer to that parameter inside the ngFor?

<ng-container *ngFor="let status of processCompStatusOrder; let i = index;>
     <div *ngIf="!!processStatus(status)">
         <clr-icon class="icon" [attr.shape]="svc.getIcon(processStatus(status))"></clr-icon>
         {{ 'base.' + processStatus(status)?.toLowerCase() | i18next }}
     </div>
</ng-container>

processStatus(status) {
     return this.process?.[status]?.process?.status; 
 }

My attempt below which doesn't work

<ng-container *ngFor="let status of processCompStatusOrder; let i = index; let p=processStatus(status)>
     <div *ngIf="!!p">
         <clr-icon class="icon" [attr.shape]="svc.getIcon(p)"></clr-icon>
         {{ 'base.' + p?.toLowerCase() | i18next }}
     </div>
</ng-container>
1

There are 1 answers

1
Jagadesan On BEST ANSWER

you can get the result and alisa like *ngIf='{status:processStatus(status)} as result

now you can access the result.status inside that ngif

`<ng-container *ngIf='{status: processStatus(status)} as result'>
 <div *ngIf="!!result.status">
     // any where else you can access this property
 </div>
</ng-container>`

Also it a better practice to use custom pipes to achieve what the process status function does. using a function inside a template will almost trigger it for every change detection and might lead to performance issues. Angular Pipe