首页 > 解决方案 > 在两个组件中使用 nativeElement

问题描述

使用角度地图(AGM)的自动完成时出现此错误,

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
TypeError: Cannot read property 'nativeElement' of undefined

, 当ElementRef用于 angular时public searchElement: ElementRef;

行出现错误:

  public latitude: number;
  public longitude: number;
  public searchControl: FormControl;
  public zoom: number;

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

  constructor(
    private mapsAPILoader: MapsAPILoader,
    private ngZone: NgZone
  ) {}

  ngOnInit() {
    //set google maps defaults
    this.zoom = 4;
    this.latitude = 39.8282;
    this.longitude = -98.5795;

    //create search FormControl
    this.searchControl = new FormControl();

    //set current position
    this.setCurrentPosition();

    //load Places Autocomplete
    this.mapsAPILoader.load().then(() => {
      let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
        types: ["address"]
      });
      autocomplete.addListener("place_changed", () => {
        this.ngZone.run(() => {
          //get the place result
          let place: google.maps.places.PlaceResult = autocomplete.getPlace();

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

          //set latitude, longitude and zoom
          this.latitude = place.geometry.location.lat();
          this.longitude = place.geometry.location.lng();
          this.zoom = 12;
        });
      });
    });
  }

在我看来组件

  <div class="form-group">
    <input placeholder="search for location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control" #search [formControl]="searchControl">
  </div>
  <agm-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom">
    <agm-marker [latitude]="latitude" [longitude]="longitude"></agm-marker>
  </agm-map>

我在两个组件中使用它,一个它工作正常,另一个它给出了错误。已尝试对元素引用使用不同的名称,但会出现相同的错误。

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

解决方案


您应该声明一个变量,例如

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

代替

public searchElement: ElementRef

这意味着searchElement变量将search模板中提到的模板引用称为(#search)wrtinput元素。


推荐阅读