属性指令:初始化时获取ElementRef宽度

问题描述 投票:1回答:1

我无法在属性指令中获取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钩子中呈现,我想不出从另一个钩子/方法获得宽度的方法。

因为我的元素ion-text不会触发任何事件,所以我无法使用HostListener,我可以在元素初始化后获得宽度。

你有什么建议吗?

谢谢!

编辑

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

ngAfterViewInit(): void {
  console.log("Element width: " + this.elementRef.nativeElement.offsetWidth); // returns 0
}
angular ionic-framework angular-directive
1个回答
1
投票

由于视图在获取元素宽度时未初始化,因此可能会出现此问题。你需要的是使用指令的另一个生命周期钩子。 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

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.