0
我有一个组件comp
,其中有一个指令findTarget
。如何使用ViewChild/ContentChild从指令中找到指令?
<comp findTarget>
</comp>
comp
持有元素与target
指令:
@Component({
selector: 'comp',
template: `
<div target>
Target
</div>
`,
directives: [Target]
})
我想从里面findTarget
指令找到target
指令:
@Directive({
selector: '[findTarget]'
})
export class FindTarget {
@ContentChild(Target) ctarget: Target;
@ViewChild(Target) vtarget: Target;
ngAfterContentInit() {
console.log('Content', this.ctarget)
}
ngAfterViewInit() {
console.log('View', this.vtarget)
}
}
,但我得到
Content undefined
View undefined
全码: http://plnkr.co/edit/kc6q445iT1TcLqexqqAg?p=preview
更新: ContentChild似乎如果我搬到target
从comp
元素插入其模板的工作: http://plnkr.co/edit/3MQj2Dv8tK036EL8GU8f?p=preview 但这不是我想要的。
什么ContentChild? –
'this.app.vComp.vtarget'我不能那样做。我不知道在我的真实应用程序中无法使用App和Comp。 –