Reputation: 85
I'm trying access the content children of a component when it is used in a different module, but the content children variable I declare is always empty.
I'm writing a component that I can use anywhere in my app. The component should have access to ng-templates inside it's tags. It will use the inputs on these templates to create a custom datagrid or table.
I can get this to work when it's all in the same module, but for some reason when it's in its own module it stops working.
See this StackBlitz for a code sample
https://angular-tfohdd.stackblitz.io
Edit: Someone asked for code even though I provided a stackblitz sample, so here it is in the question for your convenience.
The app component is using the parent component and declaring an ng-template inside of the components tags. I'm trying to get a template reference to the ng-template using a directive with an attribute selector. If My Parent was inside of the app module this code would work, but since it's inside the test module, it's not working.
app.component.html: this is inside the app module
<my-parent>
<ng-template myDirective myDirective2 title="Title1">
<div></div>
</ng-template>
</my-parent>
parent.component.ts: this is inside the test module
import { Component, Input, Directive, ContentChildren, AfterContentInit, QueryList, TemplateRef, VERSION } from '@angular/core';
@Directive({
selector: '[myDirective]'
})
export class MyDirective {
@Input() title: string;
constructor(public templateRef: TemplateRef<any>) {}
}
@Component({
selector: 'my-parent',
templateUrl: './parent.component.html'
})
export class ParentComponent implements AfterContentInit {
@ContentChildren(MyDirective) details: QueryList<MyDirective>;
ngAfterContentInit(){
console.log(this.details);
}
}
parent.component.html: this is inside the test module
Work:
<div *ngFor="let detail of details">
<div>title: {{detail.title}}</div>
<ng-container *ngTemplateOutlet="detail.templateRef">
</ng-container>
</div>
test.module.ts:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ParentComponent, MyDirective } from './parent.component';
@NgModule({
imports: [
CommonModule
],
declarations: [ParentComponent, MyDirective],
exports: [ParentComponent]
})
export class TestModuleModule { }
Upvotes: 0
Views: 1530
Reputation: 85
I was able to fix this by exporting the directive in the test module:
test.module.ts:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ParentComponent, MyDirective } from './parent.component';
@NgModule({
imports: [
CommonModule
],
declarations: [ParentComponent, MyDirective],
exports: [ParentComponent, MyDirective ]
})
export class TestModuleModule { }
Upvotes: 2