Member-only story
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: