Angular 2 ContentChild未定义 [英] Angular 2 ContentChild is undefined

查看:43
本文介绍了Angular 2 ContentChild未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取一个元素的ElementRef,该元素已使用指令作为组件的ContentChild添加了自定义属性,但是在初始化内容后对其进行记录时我未定义.你能告诉我为什么吗?

I am trying to get the ElementRef of an element on which I have added a custom attribute using a Directive as a ContentChild of a component but I get undefined when I log it after the content has been initialized. Could you please tell me why?

TestComponent:

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:

TestDirective:

@Directive({
  selector: '[test-directive]'
})
export class TestDirective {
}

AppComponent:

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=预览

Please refer to think Plunk: https://plnkr.co/edit/9KUnFWjVIbYidUtF2Avf?p=preview

推荐答案

您错过了 TestDirective 声明

查看更新后的监听器: https://plnkr.co/edit/x5rLcvJnRhnVxM7fgvvK?p=preview

See your updated plunker: 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未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆