【问题标题】:Ionic 4 - getting ElementRef property on DirectiveIonic 4 - 在指令上获取 ElementRef 属性
【发布时间】:2020-02-19 02:04:20
【问题描述】:

我需要在指令中获取 ElementRef 值以动态地将类应用于元素。

我的指令:

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

@Directive({
  selector: '[scrolling]'
})

export class ScrollingDirective {

  constructor(public renderer: Renderer2, public el: ElementRef) {
    console.log(this.el);
    console.log(this.el.nativeElement.scrollWidth);
    if (el.nativeElement.scrollWidth > el.nativeElement.clientWidth) {
      this.renderer.addClass(el.nativeElement, 'scrollear');
    }  
  }

}

然后我将指令分配给 DOM 的元素:

<ion-label scrolling>hello world</ion-label>

问题是在指令的构造函数中我无法接收元素的值,但是,使用console.log我可以正确看到值,但我无法获取它们。

我需要检索这些值,但在引用它们时值为 0。

【问题讨论】:

标签: angular ionic-framework elementref


【解决方案1】:

我认为您无法在构造函数中获取值,因为它尚未呈现。尝试通过ngAfterViewInit访问它们

【讨论】:

  • 试试这个:ngAfterViewInit() { console.log('ngAfterViewInit');控制台.log(this.el.nativeElement.clientWidth); } 并得到: ngAfterViewInit 0 :( 有什么建议吗?
猜你喜欢
  • 2019-07-19
  • 2017-04-24
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2019-11-11
  • 2017-10-06
  • 1970-01-01
相关资源
最近更新 更多