Angular 13: Dynamically insert a component into a specific DOM node

Viewed 947
1 Answers

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);
Related