I am trying to access child structural directive from parent directive.
This is how I'm trying to access the child
@Directive({
selector: '[appChildStruralDirective]'
})
export class ChildStruralDirective {
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef, private renderer: Renderer) {
this.viewContainer.createEmbeddedView(this.templateRef);
}
ngAfterViewInit(): void {
}
}
@Directive({
selector: '[appParentStruralDirective]'
})
export class ParentStruralDirective {
@ViewChild(ChildStruralDirective) viewChild: ChildStruralDirective;
@ContentChild(ChildStruralDirective) contentChild: ChildStruralDirective;
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef, private renderer: Renderer) {
this.viewContainer.createEmbeddedView(this.templateRef);
}
ngAfterViewInit(): void {
console.log('ngAfterViewInit:viewChild', this.viewChild);
console.log('ngAfterViewInit:contentChild', this.contentChild);
}
ngAfterContentChecked(): void {
console.log('ngAfterContentChecked:viewChild', this.viewChild);
console.log('ngAfterContentChecked:contentChild', this.contentChild);
}
}
@Component({
selector: 'my-app',
template: `
<h1 *appParentStruralDirective>
<span *appChildStruralDirective>Hello world</span>
</h1>
`,
})
export class App {
constructor() {
}
}
I'm not sure why the child directive is not accessible.
I have created a plunkr to demonstrate the issue.
https://plnkr.co/edit/deQC6cY4oHuNdKbzsfhE?p=preview
Please let me know why this is not working.
PS: I have used both ViewChild & ContentChild (most likely candidate) as I'm not sure which one this will fall into as these are dynamically generated elements.
You can create a service for each combination Parent-Child.
Here is plunker: https://plnkr.co/edit/zNf7iZtOQtlsSfYOfq5D?p=preview