An angular and ionic component for google places autocomplete

An angular and ionic component for google places autocomplete

Many applications need an input for inserting a city or an address.
It is not always a good idea to implement the whole logic in the controller, first of all because we can’t control so well the ngModel and secondly because we could need to use that component in different parts of the application.

I implemented this component on top of some ionic components, but it is very easy to replace the ion-label and ion-input and reuse the same code for a “vanilla” angular project.

What will get in the end of this tutorial, it is a component we can easily integrate in our forms in this way:

types restricts the results that appear in the autocomplete field (see maps api)
returnProperty is the property that we want into the ngModel, in this case just the place_id, by default you”ll get the whole gmaps object

Let’s start with the template:

Nothing special here.
We have the {{label}} passed from the external. #addressInput is needed to find the real <input> tag underneath the ion-input component, of course, the ngModel and a spinner that shows if IsPending is true (while the form is being validate)

Before to see the code of the controller which is the heart of this component, it’s important for you to have an overview of  how forms work in angular and what ControlValueAccessor is.
If you don’t know about it, I strongly advice you to read some good article like this one:

Our component relies on (@agm/core) in order to easily interact with google maps, I use it for other stuff in my app, so I’ve decided to use it even here.
In this case it helps to dynamically load the maps api:

Install it before to continue and set up your google api key in your app.module.ts

Finally, the controller (pay attention to the comments):

That’s all.
The thing I’d like to improve is

It is never advisable to directly interact with the dom, we could have problem if we export the app for other platforms not web-based.
I’ll find and post a better solution, probably based on “rederer” .
Do you have any suggestion?


The funcion  validate() is called every time the model changes, so many subscriptions occurres.
The easist, but probably not the best way to avoid it is:

It would be better to find a different way to access to FormControl object, someone pass it to the component through @input()
I’ll give you updates as soon as I find a better way, in the meanwhile any advice is encouraged.

Leave a Reply

Your email address will not be published. Required fields are marked *