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);
}
}
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.