我需要在指令中获取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。
我认为您无法在构造函数中获取值,因为它尚未呈现。尝试在ngAfterViewInit