4

So, whenever I call/click unRelatedFunction() 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)="unRelatedFunction()">test</button>

//ts

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

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

  unRelatedFunction() {
    console.log("test");
  }
Amit Kumawat
  • 114
  • 1
  • 1
  • 12

3 Answers3

2

You can use trackBy

HTML

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

TS

value(index, item){
  return item;
}

detailed explanation here

Donald Duck
  • 618
  • 2
  • 6
1

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)))
Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • hi @eliseo, thanks, but my concern is about the re-render behavior of `ngFor`. Actually, I shorten my problem by this explanation, in reality, I was creating HTML elements by using loop values by `ngFor`, but it was getting added each time on any event click. To resolve this issue I used pipe instead of calling method `create`. – Amit Kumawat Jul 07 '21 at 07:28
1

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

  • hi @rajesh, I shorten my question by this explanation, in reality, I was creating HTML elements by using loop values by `ngFor`, but it was getting added each time on any event click. To resolve this issue I used pipe instead of calling method to create. but thanks for explaining this synchronizing feature of Angular, that makes sense on my issue. – Amit Kumawat Jul 07 '21 at 09:11
  • Hi @Amit, that is great news. – Rajesh Kumar Swain Jul 07 '21 at 14:43