13

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>

1 Answer 1

40

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

2
  • Thanks, it can work. But @Input() childTemplate and @ContentChild('childTemplate') childTemplate in app-child are some kind of repeated, I can not add any @Input in app-child for some reasons, could you find another way to resolve this ?
    – Seven
    Aug 23, 2018 at 0:11
  • As I asked above, the app-child can not be changed, I could only do sth. in app-prent in my model. I thought the solution is to move the <ng-template #childTemplate></ng-template> into app-child, how do you think ?
    – Seven
    Aug 23, 2018 at 0:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.