1

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?

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165

1 Answers1

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

or

@ViewChild(HighlightDirective) directive:HighlightDirective;

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Hi Gunter. Your first option still causes the `span` to be output to the console. Your second option causes a crash. Do I need to do anything else? Here is a plunker with your solution: http://plnkr.co/edit/VrtqMMs0gSuvLkweu4FT?p=preview – BeetleJuice Sep 02 '16 at 15:41
  • If you have more than one class in one file and you refer the class, it must come before the class where the reference is used. Classes are not hoisted in TS. If you move the `HighlightDirective` above `AppComponent` it works fine http://plnkr.co/edit/3clXTT69CyWWs5faKZAN?p=preview – Günter Zöchbauer Sep 02 '16 at 15:45
  • Thanks. I put the directive in its own file and I can see that both your suggestions work (http://plnkr.co/edit/gvaa74YK6T4bldjdvjEB?p=preview). I'm curious about the 2nd notation though: In that case how does `Angular` know which specific instance I'm interested in? Suppose there were a few `HighlightDirective` instances in the view? – BeetleJuice Sep 02 '16 at 15:56
  • It doesn't ;-), it just returns the first. This is why my first variant also exists. I updated my answer. See also http://stackoverflow.com/questions/32693061/angular-2-typescript-get-hold-of-an-element-in-the-template/35209681#35209681 – Günter Zöchbauer Sep 02 '16 at 15:57