Lucien Dubois
Lucien Dubois

Reputation: 1704

Fix the TS2345: Argument of type 'HTMLElement' is not assignable to parameter of type 'HTMLInputElement'

I'm trying to setup Google Maps Places Autocomplete in an new Ionic app.

here is the problem. On the first search, I got this error in the console:

TypeError: Cannot read property 'place_id' of undefined

and this error in the terminal:

TS2345: Argument of type 'HTMLElement' is not assignable to parameter of type 'HTMLInputElement'

However, on the second search I get the place_id without any error.

Here is my (simplified) .ts file

import { Component, OnInit } from '@angular/core';
import { google } from "google-maps";
import { Platform } from '@ionic/angular';

@Component({...})
export class AddaddressPage implements OnInit {

  autocomplete:any;

  constructor(public platform: Platform) {}

    ngOnInit() {
        this.platform.ready().then(() => {
            this.autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
            this.autocomplete.setFields(['place_id']);
        });
    }

    fillInAddress() {
      var place = this.autocomplete.getPlace();
      console.log(place);
      console.log(place.place_id);
    }

}

and the input I use:

<input id="autocomplete" type="text" (change)="fillInAddress()" />

How should I proceed ?

Upvotes: 1

Views: 2423

Answers (1)

Lucien Dubois
Lucien Dubois

Reputation: 1704

After playing around, here is the trick! ViewChild and Ion-input are needed.

.html

<ion-input #autocomplete type="text"></ion-input>

.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { google } from "google-maps";
import { Platform } from '@ionic/angular';

@Component(...)
export class AddaddressPage implements OnInit {

  googleAutocomplete:any;

  @ViewChild('autocomplete') autocompleteInput: ElementRef;

  constructor(public platform: Platform) {  }

    ngOnInit() {
        this.platform.ready().then(() => {
            this.autocompleteInput.getInputElement().then((el)=>{
                this.googleAutocomplete = new google.maps.places.Autocomplete(el);
                this.googleAutocomplete.setFields(['place_id']);
                this.googleAutocomplete.addListener('place_changed', () => {
                    var place = this.googleAutocomplete.getPlace();
                    console.log(place);
                    console.log(place.place_id);
                });
            })

        });
    }

}

Upvotes: 0

Related Questions