我正在尝试获取一个元素的ElementRef,我在该元素上使用Directive作为组件的ContentChild添加了一个自定义属性,但是当我在初始化内容后记录它时,我得到了未定义。你能告诉我为什么吗?
TestComponent:
@Component({
selector: 'test-component',
template: `
<h1>Test Component</h1>
<ng-content></ng-content>
`
})
export class TestComponent implements AfterContentInit {
@ContentChild(TestDirective) child;
ngAfterContentInit() {
console.log(this.child);
}
}
TestDirective:
@Directive({
selector: '[test-directive]'
})
export class TestDirective {
}
AppComponent:
@Component({
selector: 'my-app',
declarations: ['TestComponent'],
template: `
<h1>{{title}}</h1>
<test-component>
<h2 test-directive>Test Directive</h2>
</test-component>
`
})
export class AppComponent {
title = 'Hello123!';
}
请参阅think Plunk:https://plnkr.co/edit/9KUnFWjVIbYidUtF2Avf?p=preview
答案 0 :(得分:2)
您错过了declaration
的{{1}}!
查看更新的plunker:https://plnkr.co/edit/x5rLcvJnRhnVxM7fgvvK?p=preview
TestDirective