我需要在数组中的多个输入上添加google autocomplete建议。

这是我的示例代码:

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


我得到这个错误


  TypeError:无法获取未定义或null的属性“ nativeElement”
  参考TypeError:无法获取属性'nativeElement'
  在以下位置未定义或空引用


请检查并帮助我。

最佳答案

您必须访问实现ngAfterViewInit()接口的AfterViewInit生命周期挂钩中的元素

// Import this
import {Component, Directive, Input, ViewChild,AfterViewInit,ElementRef} from '@angular/core';

export class Your_Class implements AfterViewInit {
@ViewChild("search") public searchElementRef: ElementRef;

  ngAfterViewInit() {
    console.log(this.searchElementRef); // do whatever with element
  }
}


Working Stackblitz Example

10-05 18:19