It appears that utilizing a directive to target a content child from another directive is the recommended approach (source).
However, why isn't my component able to recognize the component marked with the directive?
./my.component.ts
import {
Component,
Directive,
ContentChild,
AfterContentInit
} from "@angular/core";
@Directive({
selector: "[trigger]"
})
export class TriggerDirective {}
@Component({
selector: "app-my-component",
template: ` <ng-content></ng-content> `
})
export class MyComponent implements AfterContentInit {
@ContentChild(TriggerDirective) trigger: TriggerDirective;
ngAfterContentInit() {
console.log("===> ", this.trigger);
// output: '===> undefined'
}
}
./my.module.ts
import { NgModule } from "@angular/core";
import { MyComponent, TriggerDirective } from "./my.component";
@NgModule({
declarations: [MyComponent, TriggerDirective], // declared here
exports: [MyComponent]
})
export class MyModule {}
./app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "app-root",
template: `
<h1>Title inside app component.</h1>
<app-my-component>
<button #trigger>Click me</button>
</app-my-component>
`
})
export class AppComponent {}
./app.module.ts
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
import { MyModule } from "../my-component/my.module";
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, MyModule], // imported module here
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}