'Angular 13: Dynamically insert a component into a specific DOM node
I need to achieve something like in this question Angular 2 Dynamically insert a component into a specific DOM node without using ViewContainerRef
I got a task to use the plain google maps api within an angular/ionic project. I want to add a button as a custom control to the map, and I want to use ionic-button for this and not create the button completely in plain javascript/typescript.
But as ComponentFactoryResolver got deprecated in Angular 13, what would be the best way to do it.
Solution 1:[1]
I found myself the following solution. In the component where I include the google map the following template is used
<div class="mapcontainer" #mapContainer>
<ng-template #btnTemplate>
<ion-button class="map-button" (click)="onClick()">
{{toggleButtonText}}
</ion-button>
</ng-template>
<div class="loading-indicator">
<ion-spinner name="crescent" *ngIf="!loaded" color="primary"></ion-spinner>
</div>
</div>
As can be seen the ionic button is within a template that has a ref, so it is accessible as a view child in the angular component. And then to add the button to the google map I do the following in the typescript component code.
const btnViewRef = this.btnTemplate.createEmbeddedView();
this.app.attachView(btnViewRef);
const btnContainer = document.createElement('div');
for (const node of btnViewRef.rootNodes) {
btnContainer.appendChild(node);
}
this.map.controls
[this.googleField.maps.ControlPosition.TOP_LEFT].push(btnContainer);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HdcDst |
