0

In my code, i have a div named #map that will displayed after a condition from a for loop.

<div *ngFor="let message of fullMessagesArr">
 <div *ngIf="message.replyMap">
   <div #gmap style="width:100px;height:400px"></div>
 </div>
</div> 

My .ts file given below with initMap function.

@ViewChild('gmap') gmapElement: ElementRef;
map: google.maps.Map;

  initGMap = () => {
    const mapProp = {
      center: new google.maps.LatLng(6.9404, 79.8464),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.satellite
    };
    this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
  }

initGMap function is getting called inside sendMessage function.

7
  • Where is fullMessagesArr set? Either it's not set, or it's empty, or none of the messages get the replyMap property set Commented Sep 9, 2019 at 10:50
  • no, it is not empty, i put items to it from a API call and it is not empty, i checked that Commented Sep 9, 2019 at 10:53
  • can you show us the code for that? Commented Sep 9, 2019 at 11:00
  • error is not in the array, problem occurs when i use @viewchild and try to load the map with initGMap function Commented Sep 9, 2019 at 11:04
  • It can be a synchronisation problem. If you call initGMap before fullMessagesArr has been assigned a value, it can lead to these problems. What is printed in the console can be misleading btw Commented Sep 9, 2019 at 11:10

1 Answer 1

1

Seem like you are trying to access the element when it not visible to DOM yet so what you can do is run setTimeOut or use ngAfterContentInit life cycle hook to wait for the DOM to be render

export class AppComponent implements OnInit, OnDestroy, AfterContentInit {

    public ngAfterContentInit(): void {
       const mapProp = {
           center: new google.maps.LatLng(6.9404, 79.8464),
           zoom: 15,
           mapTypeId: google.maps.MapTypeId.satellite
       };
       this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
    }
}

or use setTimeOut

initGMap = () => {
    const mapProp = {
      center: new google.maps.LatLng(6.9404, 79.8464),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.satellite
    };
    setTimeout(() => {
         this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
    }, 3000);
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.