2016-09-17 26 views
3

我有一个指令:查询的视图中的指令无法正常工作变量

@Directive({ 
    selector: '[myDirective]' 
}) 

export class MyDirective implements AfterViewInit { 
    @ViewChild('wrapper') wrapper; 
    @ViewChild('list') list; 

    ngAfterViewInit() { 

    // Both of these are undefined 
    console.log(wrapper, list); 
    } 
} 

这需要查询的是它正在使用的视图变量

所以说我有这个模板我的部件之一,MyComponent

<div #wrapper myDirective> 
    <ul #list></ul> 
</div> 

它需要找到这些变量,但绝不指令管理要做到这一点我现在有它的方式。我猜测为什么会发生这种情况,因为该指令实际上没有视图,所以ngAfterViewInit运行得太快,并且/或者@ViewChild试图在错误的地方找到wrapperlist

如何确保指令可以找到变量?

+0

已包含它在'declarations'为模块?你在控制台中收到什么(如果有)消息? – jonrsharpe

回答

2

只需将ViewChild更改为ContentChild即可。我想它应该工作

export class MyDirective implements AfterViewInit { 
    @ContentChild('wrapper') wrapper; 
    @ContentChild('list') list; 

    ngAfterContentInit() { 
    console.log(this.wrapper, this.list); 
    } 
} 

Plunker Example

+0

不知道他们在指令上工作。 –

+1

@GünterZöchbauer我既不,但显然他们。 – Chrillewoodz