1

I have a JavaScript Listener within a Google Maps object:

map.data.addListener('click', (event) => {
      var mapElement = event.feature.getProperty('type');
      switch(mapElement){
        case 'cameras':
          var cameraID = event.feature.getProperty('trafficID');
          this.cameraService.createCamera(cameraID);
          break; ...

This 'map' Listener calls a function within a service called 'cameraService' which initialises the camera. I have a DOM object which uses Angular 2's ngIf directive to determine whether it exists:

<div *ngIf="cameraService.camera1 != null">
  <app-camera></app-camera>
</div>

My problem: ngIf doesn't run after the click event happens. Console logs show that the camera object is created, and if I click on another element (outside of the map), the view updates (ngIf change detection starts up again).

I assume this issue to do with the Angular 2 zone's - so when I click on the Google Map, it is outside of the Angular 2 zone and when I click on another element (within Angular 2), I re-enter the Angular 2 zone [Correct me if I am wrong!]... How do I manually trigger ngIf or re-enter the Angular 2 zone at the end of the click event to restart the Angular 2 change detection?

dandev91
  • 1,691
  • 3
  • 22
  • 34

1 Answers1

1

You can either use zone.run() to force the execution back into Angulars zone or you can invoke change detection manually:

constructor(private zone:NgZone, private cdRef:ChangeDetectorRef) {}

map.data.addListener('click', (event) => {
  this.zone.run(() => {
      var mapElement = event.feature.getProperty('type');
      switch(mapElement){
        case 'cameras':
          var cameraID = event.feature.getProperty('trafficID');
          this.cameraService.createCamera(cameraID);
          break; ...
  });
}

or

map.data.addListener('click', (event) => {
      var mapElement = event.feature.getProperty('type');
      switch(mapElement){
        case 'cameras':
          var cameraID = event.feature.getProperty('trafficID');
          this.cameraService.createCamera(cameraID);
          this.cdRef.detectChanges(); // <<<=== added
          break; ...
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Awesome! I ended up using: this.ngZone.run( () => this.cameraService.cameraClicked(station_key) ); and this worked perfectly! – dandev91 Oct 13 '16 at 06:23