2017-08-10 23 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) {} 
} 
相關問題