Search code examples
javascriptangulargoogle-maps-api-3ionic-frameworkangular-ngmodel

Ionic + Angular2 google maps layer event listener model binding


I have a map initialized with markers. Whenever I click on a marker I want to update Ngmodel. Eventually this should reflect in a ion-searchbar. Whenever the view loads I call initMap() which loads the map together with this listener:

google.maps.event.addListener(layer, 'click', function(e) {
      this.searchValue = e.row['name'].value;
});

in my template:

<ion-searchbar [(ngModel)]="searchValue"></ion-searchbar>

Whenever I set a value to searchValue at the declaration it does show in the ion-searchbar, however not after clicking a marker. The marker click event does work because if I console log e.row['name'].value , I get the correct value, it just not seems to bind.


Solution

  • Try importing NgZone and make use of its run()-method, to explicitly make the code run inside Angulars zone, and also trigger change detection afterwards. Also change function(e){...} to (e) => {} which is non-binding of this.

    import { Component, NgZone } from '@angular/core';
    
    @Component({
        ...
    })
    export class SomeComponent{
        someValue: string;
    
        constructor(private zone: NgZone){}
    
        initMap(){
            ...
            google.maps.event.addListener(layer, 'click', (e) => {
                this.zone.run(() => {  
                    this.searchValue = e.row['name'].value;
                });
            });
        }
    
        ...
    }