user10747832
user10747832

Reputation:

Angular 6: TypeError: Unable to get property 'nativeElement' of undefined or null reference

I got this error

TypeError: Unable to get property 'nativeElement' of undefined or null reference TypeError: Unable to get property 'nativeElement' of undefined or null reference at

Here is my sample code app.component.html

<mat-form-field *ngFor="let i of [1,2,3,4,5]" class="example-full-width form-controlNew">
  <input matInput autocomplete="off" placeholder="17 Summit Avenue" formControlName="formattedAddress" #search>
</mat-form-field>

app.component.ts

/// <reference types="@types/googlemaps" />
import {
  Component,
  OnInit,
  NgZone,
  ElementRef,
  ViewChild
} from "@angular/core";

private geocoder;
@ViewChild("search")
public searchElementRef: ElementRef;


ngOnInit() {
setTimeout(() => {
  this.setCurrentPosition();
  this.mapsAPILoader.load().then(() => {
    const autocomplete = new google.maps.places.Autocomplete(
      this.searchElementRef.nativeElement,
      {
        types: ["location"]
      }
    );
    this.geocoder = new google.maps.Geocoder();
    autocomplete.addListener("place_changed", () => {
      this.ngZone.run(() => {
        const place: google.maps.places.PlaceResult = autocomplete.getPlace();
        if (place.geometry === undefined || place.geometry === null) {
          return;
        }
        this.lat = place.geometry.location.lat();
        this.lng = place.geometry.location.lng();
        this.quickjobform.patchValue({
          location: {
            formattedAddress: place.formatted_address,
            zipcode: this.getAddressComponent(place, "postal_code", "long"),
            city_sector: this.getAddressComponent(
              place,
              "sublocality_level_1",
              "long"
            ),
            city: this.getAddressComponent(place, "locality", "long"),
            country: this.getAddressComponent(place, "country", "long"),
            latitude: this.lat,
            longitude: this.lng
          }
        });
        this.zoom = 8;
      });
    });
  });
},5000);
}

Please check and help me.

Upvotes: 2

Views: 2793

Answers (2)

this is yash
this is yash

Reputation: 533

Make sure you are using @ViewChild in the class level, because it is a property of the class and cannot be accessed inside it's methods.

You need to use .value after nativeElement in order to fetch it's value

@ViewChild('search') searchValule : ElementRef
var enteredSearchValue      = this.searchValule.nativeElement.value

Upvotes: 2

vasilv
vasilv

Reputation: 44

ViewChild is not defined in ngOnInit hook because the template is not rendered yet, thus you cannot have a reference to the element. Try to change the hook to ngAfterViewInit

Upvotes: 1

Related Questions