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

标签 javascript angular

我收到这个错误

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

这是我的示例代码 应用程序组件.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);
}

请检查并帮助我。

最佳答案

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.

您需要在nativeElement之后使用.value 才能获取它的值

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

关于javascript - Angular 6 : TypeError: Unable to get property 'nativeElement' of undefined or null reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53737984/

相关文章:

javascript - 更新数组中的多个对象

javascript - 从 id 标签中获取数字

javascript - Angular 2 中组件/视觉继承的最佳方法?

javascript - 根据鼠标点击位置定位 div

javascript - 如何从 flatTreeNode 填充树?

angular - Angular 形式问题 : AbstractControl vs FormControl

javascript - 如何使用 Javascript/jQuery 根据浏览器的窗口大小动态设置 CSS 类的高度?

javascript - 没有递归回调函数的背靠背ajax长轮询

javascript - Bootstrap-tour 未初始化

javascript - 将数组中的项目列表映射到函数参数