如何获取我的 Angular 2 指令实例的句柄?
How to get a handle to an instance of my Angular 2 directive?
Angular 2 rc 5
写成typescript 1.9
我想获得属性指令实例的句柄。我正在使用与组件一起使用的 ViewChild
,但它却为我提供了承载指令的元素的句柄。
模板
<span myHighlight #directive> Highlight me! </span>
分量
/** Want handle to the directive. Instead gives handle to the span element */
@ViewChild('directive') directive:HighlightDirective;
ngAfterViewInit(){
console.log(this.directive);
}
指令
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef, renderer: Renderer) {
renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow');
}
}
<span>
元素被打印到控制台,因此 ViewChild
没有获取我需要的内容。如何获得对指令实例的引用?
@ViewChild('directive', {read: HighlightDirective}) directive:HighlightDirective;
或
@ViewChild(HighlightDirective) directive:HighlightDirective;
但是第二种方法 returns 第一种 HighlightDirective
,不是特定的方法。
Angular 2 rc 5
写成typescript 1.9
我想获得属性指令实例的句柄。我正在使用与组件一起使用的 ViewChild
,但它却为我提供了承载指令的元素的句柄。
模板
<span myHighlight #directive> Highlight me! </span>
分量
/** Want handle to the directive. Instead gives handle to the span element */
@ViewChild('directive') directive:HighlightDirective;
ngAfterViewInit(){
console.log(this.directive);
}
指令
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef, renderer: Renderer) {
renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow');
}
}
<span>
元素被打印到控制台,因此 ViewChild
没有获取我需要的内容。如何获得对指令实例的引用?
@ViewChild('directive', {read: HighlightDirective}) directive:HighlightDirective;
或
@ViewChild(HighlightDirective) directive:HighlightDirective;
但是第二种方法 returns 第一种 HighlightDirective
,不是特定的方法。