yodalr
yodalr

Reputation: 10932

Angular 2 directive's lifecycle hook (ngAfterContentInit) not working as described in documentation

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

Answers (2)

Vega
Vega

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

Alexander Leonov
Alexander Leonov

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

Related Questions