Patricio Vargas
Patricio Vargas

Reputation: 5522

InvalidValueError: not an instance of HTMLInputElement Angular 5

I'm trying to do autocomplete for an address using the google mapsAPI in my app, but I keep getting the "InvalidValueError: not an instance of HTMLInputElement" error. Below are the things I have tried

html input inside of a form. As you can see I tried the focus trick and it didn't work either.

 <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 file

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

I tried 4 different things, no luck to get this to work

Upvotes: 0

Views: 1811

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

The template reference variable #address is tied to ngModel. You could define another one, like #address1:

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

and use it to access the element in code:

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

...

let inputElement = this.addressElement.nativeElement as HTMLInputElement;

Upvotes: 1

Related Questions