Angular — Using NgTemplateOutlet to communicate between parent and dynamic child components
--
The parent with dynamic children pattern is a common pattern in Angular that you may use when working on some complicated features, such as third party library integration. Here I would like to explain with an example using Google map:
<google-map [key]="apiKey">
<google-map-marker *ngFor="let marker of markers"
[lat]="marker.lat"
[lng]="marker.lng">
</google-map-marker>
</google-map>
The <google-map>
is the parent component, which initializes and renders the Google map. The <google-map-marker>
is the child component that can be dynamically added to create markers on the map. A common solution to this use case is to create a component-level scoped service to communicate between parent and children. Yet, I would like to introduce a more light-weighted alternative using NgTemplateOutlet
.
What is NgTemplateOutlet?
NgTemplateOutliet
is an Angular built-in directive that takes a template reference and render that template with a given context. In simple, you can imagine it as a rendering function. You pass your parameters (context) to the function, then it renders the content (template reference) based on your given context. Here is a simple example:
<ng-template #test let-word="word">
Hi, I received {{word}}
</ng-template><ng-container *ngTemplateOutlet="test; context: { word: 'Hello' }"></ng-container><br><ng-container *ngTemplateOutlet="test; context: { word: 'World' }"></ng-container>
And in your view:
Hi, I received Hello
Hi, I received World
Passing data through NgTemplateOutlet
The logic is not straight forward, but it isn’t as difficult as you may think. When using NgTemplateOutlet
to pass data between parent and children, we wrap the children with <ng-template>
with context parameters. This whole <ng-template>
is then rendered in your parent component with NgTemplateOutlet
, supplying the data needed to be passed to children via the context. Here I would like to use the NgTemplateOutlet
approach to implement an integration of the…