【问题标题】:InvalidValueError: not an instance of HTMLInputElement Angular 5InvalidValueError:不是 HTMLInputElement Angular 5 的实例
【发布时间】:2018-05-01 02:28:11
【问题描述】:

我正在尝试在我的应用程序中使用 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 种不同的方法,但没有成功

【问题讨论】:

  • 我们能看到addressElement 的声明吗?此外,输入元素是在 ngFor 循环内还是在具有 ngIf 条件的祖先内?
  • 至于“技巧”,您可以尝试:const addressInput = document.getElementById('address');,并将this.addressElement.nativeElement 替换为addressInput(尽管使用document.getElementById 不是Angular 访问元素的方式)。跨度>
  • 请出示addressElement的声明,这是最重要的。对于“技巧”,请尝试:const addressInput = document.getElementById('address') as HTMLInputElement;
  • 模板变量#address 绑定到ngModel。您应该在输入元素中定义另一个,例如#address1,并在@ViewChild('address1') 中使用它。这应该有效(而不是使用document.getElementById)。不过,我不确定它是否有助于解决其他问题。
  • @ConnorsFan 所以也许这是修复的一部分。我还注意到自动完成在模态后面,所以我添加了 `.pac-container { z-index: 10000 !important; } ' 这使它出现在模式的顶部。非常感谢这个人!!如果您愿意,请将其作为答案发布,以便我将其作为正确答案,您可以获得一些积分

标签: angular google-maps google-maps-api-3


【解决方案1】:

模板引用变量#address 绑定到ngModel。你可以定义另一个,比如#address1:

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

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

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

...

let inputElement = this.addressElement.nativeElement as HTMLInputElement;

【讨论】:

    猜你喜欢
    • 2016-03-07
    • 2017-11-25
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    相关资源
    最近更新 更多