Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent : ngFor getting re-render on any click event

So, whenever I call someFunction() it makes the ngFor loop re-render again. Is there any way to avoid this unwanted connection? I am using Angular 12.

please let me know if I am missing any required information. Thanks

//html

<div *ngFor="let item of arr">{{ create(item) }}</div>

<button type="button" (click)="someFunction()">test</button>

//ts

   arr = [1, 2, 3, 4, 5, 6, 7];

   create(val) {
    console.log("again ?");
    return val + 1
  }

  someFunction() {
    console.log("test");
  }
like image 570
Amit Kumawat Avatar asked Oct 20 '25 03:10

Amit Kumawat


2 Answers

You can use trackBy

HTML

*ngFor=“let item of arr; trackBy: value”

TS

value(index, item){
  return item;
}

detailed explanation here

like image 138
Donald Duck Avatar answered Oct 21 '25 21:10

Donald Duck


Amit, in general is a bad idea using a function into a *ngFor. a better approach is create a new object or add a new property to our array of object and show this properties.

arr = [1, 2, 3, 4, 5, 6, 7]; //<--your original array
arrNew=this.arr.map(x=>({value:x,property:this.create(x))) //<--a new array of object

<!--iterate over arrNew-->
<div *ngFor="let item of arrNew">{{ item.property }}</div>

See that, in this way, the function it's only called so many times elements has the array

If we has an array of object

arr = [{id:1}, {id:2},{id:3},{id:4}]; //<--your original array

We can, in ngOnInit

//or add a new property   
this.arr.forEach(x=>{
    x.property=this.create(x.id)
}

//or create a new array with all the properties of x (using spread operator)
//and a new property
this.arrNew=this.arr.map(x=>({...x,property:this.create(x.id)))
like image 21
Eliseo Avatar answered Oct 21 '25 22:10

Eliseo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!