Search⌘ K
AI Features

Add Google Places Autocomplete

Explore how to enhance an Angular event creation form by integrating Google Places Autocomplete. Learn to use Angular's ViewChild to reference input elements, NgZone to manage asynchronous updates, and MapsAPILoader to load the Google Places API. This lesson guides you through setting up autocomplete for city input, handling asynchronous data, and updating the form to improve user experience.

Below is the updated code so far:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>LetsGetLunch</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>
Updated create event form

Update event creation form

Address the location input.

  1. Uncomment the HTML for location.
  2. On the input element, add the template variable #city. We’ll reference this shortly once we implement the autocomplete for Google Places.
  3. Add autocorrect="off" to prevent the browser from attempting to autocorrect any text within this input, because Google will handle it for us.
HTML
<!--src/app/event/event-create/event-create.component.html-->
<div class="form-group">
<label>Location</label>
<input class="form-control"
#city
autocorrect="off"
formControlName="location">
</div>

Adding autocomplete functionality

From here, update our imports from @angular/core, adding NgZone, ElementRef, and ViewChild.

TypeScript 3.3.4
// src/app/event/event-create/event-create.component.ts
import { Component, OnInit, NgZone, ElementRef, ViewChild } from '@angular/core';
  1. ViewChild allows us to get an element from our view so that we have a reference to that element within our component.
  2. Because ViewChild is a reference to an element within our view, we’ll set its type as ElementRef.
  3. We’ll cover what NgZone does soon, when we add the Google
...