David Aguirre
David Aguirre

Reputation: 1410

Angular 2 Google places autocomplete event listener not responding

I have an input field with Google places autocomplete. Everything works as expected, but the event listener is not responding once a selection is made from the autocomplete dropdown. Shouldn't that be the expected behavior? Here is my code.

let input: any = this.geocodeTest.nativeElement;
var searchBox = new google.maps.places.Autocomplete(input);
    searchBox.addListener("places_changed", () => {
        this._ngZone.run(() => {
            console.log('listening');
            var places = searchBox.getPlaces();
            if (places.length == 0) {
                return;
            }
        })
    });

The code currently lives within the ngOnit()

Upvotes: 2

Views: 358

Answers (1)

Pengyy
Pengyy

Reputation: 38171

As you mentioned you are running these code in ngOnInit, and this is the reason because DOM elements are only avalible after AfterViewInit lifehook.

you have to move your code to ngAfterViewInit.

Plunker Demo.

Upvotes: 1

Related Questions