Amit Kumawat
Amit Kumawat

Reputation: 144

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

Upvotes: 4

Views: 2671

Answers (3)

Rajesh Kumar Swain
Rajesh Kumar Swain

Reputation: 121

This is default change detection in Angular, It compare the values of templates expression before and after a browser event to see if something changes. I can recommended here do not force to avoid this synchronizing feature of Angular. I think you are worried because create() is calling after hitting this unRelatedFunction(). I am not sure why you need Create() in for loop, Will you please elaborate in details what you are going to do in Create() so I can suggest any alternative solution.

Thanks Rajesh

Upvotes: 1

Eliseo
Eliseo

Reputation: 57939

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

Upvotes: 1

Donald Duck
Donald Duck

Reputation: 638

You can use trackBy

HTML

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

TS

value(index, item){
  return item;
}

detailed explanation here

Upvotes: 2

Related Questions