修复 TS2345:'HTMLElement' 类型的参数不可分配给 'HTMLInputElement' 类型的参数

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

我正在尝试在新的 Ionic 应用程序中设置 Google 地图地点自动完成

问题来了。在第一次搜索时,我在控制台中收到此错误:

TypeError: Cannot read property 'place_id' of undefined

终端出现这个错误:

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

但是,在第二次搜索时,我得到了 place_id,没有任何错误。

这是我的(简化的).ts 文件

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);
    }

}

以及我使用的输入:

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

我应该如何进行?

玩转之后,诀窍来了!需要 ViewChild 和 Ion-input。

.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);
                });
            })

        });
    }

}