*ngFor executes many times in Angular

Issue

Why *ngFor is executing many times?
And why in the AfterViewInit the offsetTop of the div is zero?

<ul *ngFor="let chat of chats">
  <div id="chat{{chat.id}}">{{printItem(chat)}}</div>
</ul>
export class HomePage implements AfterViewInit {

  chats:any[]=[
    {id:1},
    {id:2},
    {id:3},
  ];

  ngAfterViewInit() {
    console.log('after view init');
    let chat:HTMLElement|null = document.querySelector("#chat3");
    console.log('offsetTop',chat?.offsetTop);
  }

  printItem(chat:any){
    console.log('chat',chat.id);
  }

}

enter image description here

Solution

I found a solution in the docs: https://ionicframework.com/docs/angular/lifecycle

Ionic has two events after the view is rendered:
ionViewWillEnter
ionViewDidEnter

I only needed to add one of these methods in my ts file:

  ionViewDidEnter(){
    console.log('ionViewDidEnter');
    let phone6:HTMLElement|null = document.querySelector("#phone6");
    if(phone6 && phone6.offsetTop){
      let top = phone6.offsetTop;
      console.log(top);
    }
  }

  ionViewWillEnter(){
    console.log("ionViewWillEnter")
    let phone6:HTMLElement|null = document.querySelector("#phone6");
    if(phone6 && phone6.offsetTop){
      let top = phone6.offsetTop;
      console.log(top);
    }
  }

Answered By – danilo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published