首页 > 解决方案 > InvalidValueError:不是 HTMLInputElement Angular 5 的实例

问题描述

我正在尝试在我的应用程序中使用 google mapsAPI 对地址进行自动完成,但我不断收到“InvalidValueError:不是 HTMLInputElement 的实例”错误。以下是我尝试过的事情

表单内的 html 输入。如您所见,我尝试了聚焦技巧,但也没有用。

 <input id="address" type="text" name="address" #address="ngModel" [(ngModel)]="markersService.selectedMarker.address" placeholder="Address" 
    autocorrect="off"
    autocapitalize="off"
    spellcheck="off"
    class="inputFields"
    required
    (focus)="autocompleteSearch()"/>

.ts 文件

 //I implemented this in an app with Angular 4 and it worked, now with Angular5 it' doesn't
 ngAfterViewInit() {
    this.autocompleteSearch();
 }


  autocompleteSearch() {
    /*
    I tried this trick based on some answers I saw in different places, but it didn't work
    var addressInput = document.getElementById('address').getElementsByTagName('input')[0];
    of course I was passing this in the code below instead of the addressElement
    */
    this.mapsAPILoader.load().then(
      ()=>{
        let autocomplete = new google.maps.places.Autocomplete(this.addressElement.nativeElement, { types:["address"]});
        autocomplete.addListener('places_changed', ()=> {
          this.ngZone.run(()=> {
            let place: google.maps.places.PlaceResult = autocomplete.getPlace();

            if(place.geometry === undefined || place.geometry === null) {
              return;
            }
          });
        })
      }
    )
  }

我尝试了 4 种不同的东西,没有运气让它工作

标签: angulargoogle-mapsgoogle-maps-api-3

解决方案


模板引用变量#address绑定到ngModel. 您可以定义另一个,例如#address1

<input #address1 #address="ngModel" ... >

并使用它来访问代码中的元素:

@ViewChild('address1') public addressElement: ElementRef;

...

let inputElement = this.addressElement.nativeElement as HTMLInputElement;

推荐阅读