0

My final goal is to build a goolgle map compoment with Angular2.

Google map has its own library, and it can be initialized using <script> tag with or without callbak.

http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initialize

I want to use this callback function to initialize an angular2 component or invoke a function of a angular2 component. e.g.,

http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=MapCompnent.initMap

Since it is a static method, it seems not possible for me.

Another way I approach is is to check google maps variable like this

get googleMapReady() {
  return window.google.maps;
}

and use it with *ngIf="googleMapReady".

Before I try the second approach, I was wondering if it is possible to call Angular2 component instance function from window level callbacks?

If so, then where can I find those examples?

allenhwkim
  • 27,270
  • 18
  • 89
  • 122

1 Answers1

1

Googleapis looks in window scope for the method. Assign a method to window and pass it's name to the URL.

This might be helpful as well Angular 2 - communication of typescript functions with external js libraries

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks for the answer. Why is it related zone? I read it but I do not understand zone is involved in this answer http://stackoverflow.com/a/35297044/454252 – allenhwkim Jun 10 '16 at 22:35
  • You can imaging Angulars zone like a bubble where Angular runs in. Certain APIs like `addEventHandler`, `setTimeout`, ... are modified when they called by the "bubble". Angulars zone patches them to notify Angular every time they have happened. This is when Angular runs change detection. When you pass a method reference to `window.xxx` and it is called from outside the "bubble" then Angular won't notice when this happened and doesn't run change detection. This leads to annoying bugs where you can see in the debugger or by `console.log(xxx)´ that the model changed, but the view doesn't update. – Günter Zöchbauer Jun 11 '16 at 08:34
  • With `zone.run(...)`, you make the code to run inside the "bubble" and Angular knows when it has to run change detection. Angulars change detection is a very smart concept and extremly efficient, but in some situations it needs some "manual" support to be able to do it's work with full efficiency. – Günter Zöchbauer Jun 11 '16 at 08:35