BeetleJuice BeetleJuice - 3 months ago 12
TypeScript Question

How to get a handle to an instance of my Angular 2 directive?

Angular 2 rc 5
written with
typescript 1.9


I'd like to get a handle to the instance of my attribute directive. I'm using
ViewChild
which works with components, but it instead gives me a handle to the element that hosts the directive.

template

<span myHighlight #directive> Highlight me! </span>


component

/** Want handle to the directive. Instead gives handle to the span element */
@ViewChild('directive') directive:HighlightDirective;

ngAfterViewInit(){
console.log(this.directive);
}


directive

@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef, renderer: Renderer) {
renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow');
}
}


Running plunker

The
<span>
element is printed to the console, so
ViewChild
is not grabbing what I need. How can I get a reference to the directive instance?

Answer
@ViewChild('directive', {read: HighlightDirective}) directive:HighlightDirective;

or

@ViewChild(HighlightDirective) directive:HighlightDirective;

but this 2nd approach returns the first HighlightDirective, not a specific one.