我试图获取一个元素的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: plnkr.co/edit/9KUnFWjVIbYidUtF2Avf?p=预览
Please refer to think Plunk: plnkr.co/edit/9KUnFWjVIbYidUtF2Avf?p=preview
推荐答案您错过了 TestDirective 的声明!
查看更新后的监听器: plnkr.co/edit/x5rLcvJnRhnVxM7fgvvK?p=preview
See your updated plunker: 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 './appponent'; import { TestComponent } from './testponent'; import { TestDirective } from './test.directive'; @NgModule({ imports: [ BrowserModule, FormsModule, HttpModule, ], declarations: [ AppComponent, TestComponent, TestDirective ], bootstrap: [ AppComponent ] }) export class AppModule { }更多推荐
Angular 2 ContentChild未定义
发布评论