2

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.

Vega
  • 27,856
  • 27
  • 95
  • 103
HdcDst
  • 41
  • 1
  • 4

1 Answers1

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);
HdcDst
  • 41
  • 1
  • 4
  • thanks for sharing your solution! – Eliseo Mar 22 '22 at 20:07
  • @Eliseo This is the solution for my use case. But I still ask myself if there is also a solution to do it with a component class. – HdcDst Mar 23 '22 at 04:53
  • 1
    Have the same issue, so far I am using ComponentFactoryResolver as there doesn't seem to be a way to do it with new api :( – Kaminari Apr 03 '22 at 14:11