需要在多个输入中添加Google自动填充框

时间:2018-12-17 11:43:40

标签: javascript node.js angular

我需要在数组中的多个输入上添加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'   在

处未定义或为空的引用

请检查并帮助我。

2 个答案:

答案 0 :(得分:2)

您必须访问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

答案 1 :(得分:0)

您必须在此处使用ViewChildren。您在#search中继器中渲染*ngFor东西-这意味着有很多东西,因此Angular无法确定您想要哪一个。因此,您可以使用ViewChildren来完成此操作,如下所示:

@ViewChildren('search') searchButtons; // these are your search things.

Here's一个示例,在这里说明了一些问题。