Angular 2 ContentChild 未定义

标签 angular

我正在尝试获取一个元素的 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/

相关文章:

Angular Material 自定义主题 - 为什么 mat-palette 需要 4 个变量?

angular - rxjs 中的嵌套 HTTP 控制流

javascript - TSLint 烦人的消息

css - Bootstrap 在 Angular 6 中无法正常工作

html - html中元素之间的间距

angular - '"类型的参数 "' is not assignable to parameter of type ' "prototype"' jasmine

html - Angular Material : how to set floatPlaceholder to never

angular - NativeScript 找不到 Angular 组件

html - 如何在 Angular 中设置我自己的 CSS 和 HTML

javascript - 无需ajax或在网络选项卡中记录请求即可更新数据 - Websockets