Reputation: 40936
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');
}
}
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
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