Angular 2 指令的生命周期挂钩 (ngAfterContentInit) 未按照文档中的描述工作

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

我正在尝试获取元素的 offsetLeft,但我得到的值不正确,除非我使用 setTimeout。

基本上在指令中我有这个:

ngAfterContentInit() {
    console.log(this.el.nativeElement.offsetLeft);
}

文档为 ngAfterContentInit "Lifecycle hook that is called after a directive's content has been fully initialized." 说明了这一点。但是它没有返回 40px,而是 returns 8px(甚至不确定它从哪里得到 8)。

知道为什么它不起作用吗?是不是因为指令的根元素不被视为指令的一部分,只有它的子元素才是?

我认为这应该可行:

ngAfterContentInit() {
    setTimeout(() => {
        console.log(this.el.nativeElement.offsetLeft);
    });
}

这是因为目前 ngAfterContentInit() 火灾 children 仍未渲染 - 所以您需要给 angular 时间来完成。

如果您不想使用超时,请按以下语法使用 AfterViewChecked:

start = true;
.....
ngAfterContentChecked() {
    if (this.start){
         console.log(this.el.nativeElement.offsetLeft);
    }
    this.start = false;
}