Нужно добавить гугл автозаполнение в поле множественного ввода - PullRequest
0 голосов
/ 17 декабря 2018

Мне нужно добавить предложение автозаполнения Google при множественном вводе в массиве.

Вот мой пример кода:

<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: Невозможно получить свойство 'nativeElement' с неопределенной или нулевой ссылкой TypeError: Невозможно получить свойство 'nativeElement' с неопределенной или нулевой ссылкой на

Пожалуйста, проверьте и помогите мне.

Ответы [ 2 ]

0 голосов
/ 17 декабря 2018

Вы должны использовать ViewChildren здесь.Вы визуализируете свою вещь #search в *ngFor повторителе - это означает, что их несколько, поэтому Angular не может решить, какой вы хотите.Таким образом, вы делаете это с помощью ViewChildren вместо этого, например так:

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

Вот пример, иллюстрирующий некоторые проблемы здесь.

0 голосов
/ 17 декабря 2018

Вы должны получить доступ к элементу в 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
  }
}

Пример работы с Stackblitz

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...