Reputation: 10932
I'm trying to get element's offsetLeft, but I get incorrect value unless I use setTimeout.
Basically in the directive I have this:
ngAfterContentInit() {
console.log(this.el.nativeElement.offsetLeft);
}
The documentation states this for ngAfterContentInit "Lifecycle hook that is called after a directive's content has been fully initialized.". But instead of returning 40px it returns 8px (not even sure where it gets that 8).
Any ideas why it isn't working? Is it because the root element of the directive is not considered part of the directive and only it's children are?
Upvotes: 2
Views: 2399
Reputation: 28738
If you don't wish to use the timeout, use AfterViewChecked with this syntax:
start = true;
.....
ngAfterContentChecked() {
if (this.start){
console.log(this.el.nativeElement.offsetLeft);
}
this.start = false;
}
Upvotes: 2
Reputation: 4794
I think this should work:
ngAfterContentInit() {
setTimeout(() => {
console.log(this.el.nativeElement.offsetLeft);
});
}
This is because at the moment ngAfterContentInit()
fires children are still not rendered - so you need to give angular time to do that.
Upvotes: 4