Reputation: 390
In this case, the app-child can not be changed, which means you can only operate the app-parent. My opinion is finding a way to insert the template in app-child, is there a function which like Renderer2.insert(parent, newItem, childRef)
or another solution ?
Look at https://stackblitz.com/edit/insert-template-to-child-component for detail.
app.component.html
<app-parent>
<ng-template #childTemplate>
how to insert this template in app-child
</ng-template>
</app-parent>
parent.component.html
<app-child>
<!-- <ng-template #childTemplate>
this is work, but I need to input the template in app-parent content
</ng-template> -->
</app-child>
child.component.html
<ng-container [ngTemplateOutlet]="childTemplate"></ng-container>
Upvotes: 15
Views: 21958
Reputation: 6854
You can pass the template as an @Input()
to the child
parent.component.html
<ng-template #childTemplate></ng-template>
<app-child [childTemplate]="childTemplate"></app-child>
child.component.ts
@Input()
childTemplate: TemplateRef<any>;
child.component.html
<ng-container [ngTemplateOutlet]="childTemplate"></ng-container>
You can use this same strategy to pass the template down multiple levels if needed.
More detailed information: https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/#configurablecomponentswithtemplatepartialinputs
Upvotes: 40