我正在尝试获取一个元素的 ElementRef,我在该元素上使用 Directive 作为组件的 ContentChild 添加了自定义属性,但在内容初始化后记录它时我得到了 undefined。你能告诉我为什么吗?
测试组件:
@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);
}
}
测试指令:
@Directive({
selector: '[test-directive]'
})
export class TestDirective {
}
应用组件:
@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
最佳答案
您错过了TestDirective
的声明
!
查看更新后的插件:https://plnkr.co/edit/x5rLcvJnRhnVxM7fgvvK?p=preview
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { TestComponent } from './test.component';
import { TestDirective } from './test.directive';
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
],
declarations: [
AppComponent,
TestComponent,
TestDirective
],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
关于Angular 2 ContentChild 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39598072/