BeetleJuice
BeetleJuice

Reputation: 40936

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?

Upvotes: 1

Views: 788

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657937

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

or

@ViewChild(HighlightDirective) directive:HighlightDirective;

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

Upvotes: 1

Related Questions