2017-08-10 25 views
1

我创建了一个绑定到组件变量的指令,并在其模板中使用。我希望能够引用正在使用它的元素。如何获取与其关联的指令中的元素ref? Angular

例如使用指令的组件模板

<div [directiveBinding]="componentVar"></div> 

例如,指令

export class MyDirective { 
    @Input('directiveBinding') varFromComponent; 
} 

如何在指令中引用div元素ref?

回答

3

您应该在构造函数中注入ElementRef。要访问HTMLDivElement,请使用this.elementRef.nativeElement

export class MyDirective { 
    @Input('directiveBinding') varFromComponent; 

    constructor(private elementRef: ElementRef) {} 
} 
相关问题