Search code examples
angularangular7angular8

How to call method once instead some times?


I have the following structure DOM in angular:

<div
      class="column"
      *ngFor="let cols of numberReturn(cols); let c = index"
      (click)="select(getMatrix(r, c))"
      title="{{ getMatrix(r, c).title }}"
      [ngClass]="{ active: isToolSelected(getMatrix(r, c)) }"></div>

As you can see I call sometimes getMatrix(r, c).

How to call this once and pass result everywhere like:

let r = getMatrix(r, c);
(click)="select(r)"
title="{{ r.title }}"

Solution

  • you can attach the value of getMatrix(r, c) with each object of your cols array inside numberReturn and access by key for example your numberReturn will look like

    numberReturn(cols){
    var retVal=[];//array your return here
    retVal.forEach((item,index)=>{
    item['matrixVal']=this.getMatrix(this.r,index);
    })
    }
    

    then on ui

    <div
          class="column"
          *ngFor="let cols of numberReturn(cols); let c = index"
          (click)="select(cols.matrixVal)"
          title="{{ cols.matrixVal.title }}"
          [ngClass]="{ active: isToolSelected(cols.matrixVal) }"></div>