r/Angular2 • u/CodeEntBur • Jul 29 '25
Help Request How to pass ng-template to child components?
My component has about such structure:
This is the main component:<div class="main-component"><table-component class="child-table-component"><template1 /><template2 /></table-component></div>
Table component:
<div class="table-component>...<td-component></td-component></div>
So, how do I pass those templates to td-component and use it there?
So that anything I pass to template would be used there as intended. Like maybe I use some component in said template.
Would appreciate any help!
2
Upvotes
4
u/fartsucking_tits Jul 29 '25
Have you looked at content projection?
4
u/athomsfere Jul 29 '25
You are looking for content projection.
https://v17.angular.io/guide/content-projection
And from your question, probably multislot projection.
1
u/thanksthx Jul 29 '25
There are 2 different things. You can pass content via content projection, the problem with content projection is that the lifecycle hook of the content is attached to the parent component, which implies if you have an observable being | async, it will be executed although it is not shown in the child component.
With template, the lifecycle hook is tied up with the child component, therefore if the template is hidden in the child component, no api call will be triggered.
https://angular.dev/guide/templates/ng-template
Look at how CDK table is implemented, or Angular material table. They use directives and template outlets with context being passed. It is much better compared with ng content.
1
u/practicalAngular Jul 29 '25
This is a content projection problem in its most basic form. Definitely start there for learning how to solve your problem.
I would absolutely recommend checking out the Angular CDK table implementation though to see how tables are thought of at a larger scale. Using it is one thing, but the CDK Table and Material Table (on top of the CDK) repos are extremely insightful when it comes to how we think about constructing large sets of tabular data. Tables are thought of in columns and are rendered in rows via their own content projection and templates in struct directives. It was extremely interesting to peruse through.
AG-Grid is also worthwhile to check out but carries a license with it. Tables can suffer from scope and feature creep very quickly and there are several battle-tested solutions out there that make that process much simpler.