angular - 属性指令 : Get an ElementRef width upon init

我无法在属性指令中获取 ElementRef 的宽度,因为它始终等于 0

我定义属性指令的元素是:

<ion-text myCustomDirective>Test Text</ion-text>

指令的实现是这样的:

import { Directive, ElementRef, OnInit } from '@angular/core';

@Directive({
  selector: '[myCustomDirective]'
})
export class MyCustomDirective implements OnInit {

  private element: any;

  constructor(
    private elementRef: ElementRef
  ) { }

  ngOnInit() {
    this.element = this.elementRef.nativeElement;
    console.log("Element width: " + this.element.offsetWidth) //The width here is always equal to 0
  }
}

我尝试了不同的方法和属性,例如 clientWidthgetComputedStyle(this.element)['width'],但我总是得到 0.

我认为问题在于该元素尚未在 onInit Hook 中呈现,我想不出从另一个 Hook /方法获取宽度的方法。

因为我的元素 ion-text 没有触发任何事件,所以我无法使用 HostListener 来获取元素初始化后的宽度。

你有什么建议吗?

谢谢!

编辑

即使尝试使用 ngAfterViewInit() 钩子(Hook)也会返回 0 的宽度:

ngAfterViewInit(): void {
  console.log("Element width: " + this.elementRef.nativeElement.offsetWidth); // returns 0
}

最佳答案

此问题可能是由于在获取元素宽度时未初始化 View 而引起的。你在这里需要的是使用指令的另一个生命周期钩子(Hook)。 ngAfterViewInit()

这是解决方案

import { Directive, ElementRef, OnInit, AfterViewInit } from '@angular/core';

@Directive({
  selector: '[myCustomDirective]'
})
export class MyCustomDirective implements OnInit, AfterViewInit {

  private element: any;

  constructor(
    private elementRef: ElementRef
  ) { }

  ngOnInit() {}

  ngAfterViewInit() {
    this.element = this.elementRef.nativeElement;
    console.log("Element width: " + this.element.offsetWidth) //The width here is always equal to 0
  }
}

Here is solution on stackblitz

希望这对您有所帮助。

关于angular - 属性指令 : Get an ElementRef width upon initialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54871474/

相关文章:

android - 通过 XML 设置选中状态

firefox - 如何在 Amazon Linux (EC2) 实例上安装 GTK3 和 Fire

javascript - 如何防止在 Angular 4+ 中更改查询字符串时页面刷新/重新加载?

Android WebRTC 不适用于不同的网络 - 无视频

scala - 使用 MemSQL 中的分区下推在 Spark 中启用并行化

ubuntu-16.04 - 设置了 CATALINA_PID 但指定的文件不存在

java - Reactor:检测空信号以能够作用于空Mono

java - 自动禁用完整线程转储

xcode - 我的应用程序有时会导致 Mac 10.12 上的 WindowServer 高 CP

google-chrome - 谷歌登录 "error": "popup_closed_by_use