3

I have an angular layout like this, and I'd like to change the Header section in the parent component from the child component. enter image description here

I googled this question, but I only see the articles on passing a template from the parent component to the child component.

Is there a way to pass a template from the child component to the parent component?

Or is there any way to inject a component to the header section in the parent from the child component?

I know I can pass values to the parent, but I need to pass either a template or a component.

jong shin
  • 682
  • 1
  • 5
  • 19
  • 3
    Does this answer your question? [Angular pass a Component as ng-template of another Component](https://stackoverflow.com/questions/51171350/angular-pass-a-component-as-ng-template-of-another-component) – Raven Aug 12 '20 at 21:24

1 Answers1

5

this idea is not very good from the architecture point of view, considering how some components should affect other components, root-to-leaves data flow and angular change detection. but it is still possible

// parent.ts
setHeaderTemplate(templateRef: TemplateRef) {
  this.headerTemplate = templateRef
}
// parent.html
<div *ngTemplateOutlet="template">
</div>
// child.ts
@ViewChild(TemplateRef) headerTpl: TemplateRef;
constructor(private parent: ParentComponent) {}

ngAfterViewInit() {
  Promise.resolve().then(() => this.parent.showHeaderTemplate(this.headerTpl));
}
// child.html
<ng-template #header>
  hello header
</ng-template>

note that "showing" the template logic in the child is done in async code. This is done because of the change detection nature of angular as at the momeny ngAfterViewInit is evaluated change detection is already done on the parent component.

Andrei
  • 10,117
  • 13
  • 21