Reputation: 3861
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:
@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!';
}
Please refer to think Plunk: https://plnkr.co/edit/9KUnFWjVIbYidUtF2Avf?p=preview
Upvotes: 3
Views: 2268
Reputation: 16917
You missed the declaration
of your TestDirective
!
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 {
}
Upvotes: 4