skip to Main Content

It seems of though the ngFor directive only allows for a single reference when creating google map map markers.
How could I create unique references for each marker in my array?

The result I’m getting is that the markers are all created but when displaying the info window, I am presented with the same info in the info window on each one.

 ` <map-marker 
    *ngFor="let marker of markers"
    #mark="mapMarker"
    [position]="marker.position"
    [title]="marker.title"
    [icon]="marker.icon"
    (mapClick)="openInfoWindow(mark)">
  </map-marker>

  <map-info-window>
    Name: {{pageName}} <br>
    Type: {{type}} <br>
    Status: <br>
    <button type = "button"
    (click)="SetPage(pageName)">Open Page</button>
  </map-info-window>`

I have tried putting the reference both inside and outside of the ngFor however the result is the same. Any ideas?

2

Answers


  1. The issue you’re facing might be related to how the references are handled in the loop. If you want unique references for each marker, you can generate dynamic references using an index.
    Please note i did not test this code just a sample

    <ng-container *ngFor="let marker of markers; let i = index">
      <map-marker 
        #mark="mapMarker"
        [position]="marker.position"
        [title]="marker.title"
        [icon]="marker.icon"
        (mapClick)="openInfoWindow(markers[i])">
      </map-marker>
    
      <map-info-window *ngIf="markers[i]">
        Name: {{markers[i].pageName}} <br>
        Type: {{markers[i].type}} <br>
        Status: <br>
        <button type="button" (click)="SetPage(markers[i].pageName)">Open Page</button>
      </map-info-window>
    </ng-container>
    
    Login or Signup to reply.
  2. Try to explicitly split the structural directive *ngFor from the local #mark assignation. Also unless you need to pass a reference on the map-marker component, you might not need the #mark at all.

    <ng-container *ngFor="let marker of markers">
    <map-marker 
        [position]="marker.position"
        [title]="marker.title"
        [icon]="marker.icon"
        (mapClick)="openInfoWindow(marker)">
      </map-marker>
    </ng-container>
    

    Also think about adding a trackBy function to prevent glitches

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search