Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google autocompleter place doesn't work in the Child Component in Angular 2

I was using the googleplace directive for the Google places autocompletor. It works when I use this directive in AppComponent as shown in the link but doesn't work when I used it in the child Components.

app.routes.ts

enter image description here

import { provideRouter, RouterConfig }  from '@angular/router';

import { BaseComponent }  from './components/base/base.component';
import { DashboardComponent }  from './components/dashboard/dashboard.component';


const routes: RouterConfig=
    [
        {path:"",redirectTo:"/admin",pathMatch:'full'}, 

        {path:"admin",component:BaseComponent,
            children:[
                    { path: '', component: BaseComponent},
                    { path: 'dashboard', component: DashboardComponent},
                ]
         }

    ];


export const appRouterProviders = [
  provideRouter(routes)
];

main.ts enter image description here

import {bootstrap}    from '@angular/platform-browser-dynamic';
import {AppComponent} from './app.component';
import {appRouterProviders} from './app.routes';


bootstrap(AppComponent,[appRouterProviders]);

app.component.ts enter image description here

import {Component} from '@angular/core';
import {ROUTER_DIRECTIVES} from '@angular/router';


@Component({
    selector : 'my-app',
    template:  `
            <router-outlet></router-outlet>
        `    ,
        directives:[ROUTER_DIRECTIVES]
})
export class AppComponent {

}

base.component.ts enter image description here

import {Component,OnInit} from '@angular/core';
import { provideRouter, RouterConfig,ROUTER_DIRECTIVES,Router }  from '@angular/router';



@Component({
    selector: 'app-base',
    templateUrl:"../app/components/base/base.html",
    directives:[ROUTER_DIRECTIVES],
    precompile:[]

})



export class BaseComponent implements OnInit{

        constructor(private _router:Router){}

        ngOnInit():any{

            this._router.navigate(["admin/dashboard"]);
        }
}

base.html has <router-outlet></router-outlet> has its content

dashboard.component.ts enter image description here

import {Component,OnInit} from '@angular/core';

import { provideRouter, RouterConfig,ROUTER_DIRECTIVES,Router }  from '@angular/router';
import {GoogleplaceDirective} from './../../../directives/googleplace.directive';



@Component({
    selector: 'dashboard',
   template:`
        <input type="text" [(ngModel)] = "address"  (setAddress) = "getAddress($event)" googleplace/>
   `,
    directives:[ROUTER_DIRECTIVES,GoogleplaceDirective]
})

export class DashboardComponent implements OnInit{

        constructor(private _router:Router){}

        ngOnInit():any{

            // this._router.navigate(["dashboard/business"]);
        }

        public address : Object;
       getAddress(place:Object) {       
           this.address = place['formatted_address'];
           var location = place['geometry']['location'];
           var lat =  location.lat();
           var lng = location.lng();
           console.log("Address Object", place);
       }
}

googleplace.directive

import {Directive, ElementRef, EventEmitter, Output} from '@angular/core';
import {NgModel} from '@angular/common';

declare var google:any;

@Directive({
  selector: '[googleplace]',
  providers: [NgModel],
  host: {
    '(input)' : 'onInputChange()'
  }
})
export class GoogleplaceDirective  {
  @Output() setAddress: EventEmitter<any> = new EventEmitter();
  modelValue:any;
  autocomplete:any;
  private _el:HTMLElement;


  constructor(el: ElementRef,private model:NgModel) {
    this._el = el.nativeElement;
    this.modelValue = this.model;
    var input = this._el;
    this.autocomplete = new google.maps.places.Autocomplete(input, {});
    google.maps.event.addListener(this.autocomplete, 'place_changed', ()=> {
      var place = this.autocomplete.getPlace();
      this.invokeEvent(place);
    });
  }

  invokeEvent(place:Object) {
    this.setAddress.emit(place);
  }


  onInputChange() {
  }
}

index.html enter image description here

Output: enter image description here

Update:

Found that, it works perfectly when there is one router-outlet tag in the project, but fails to work when we have nested router-outlet as above example has nested router-outlet

Github link here

Is there any issue with directive code with child components of a component? Please let me know how I can resolve this issue.

like image 288
Shoaib Chikate Avatar asked Aug 10 '16 15:08

Shoaib Chikate


1 Answers

The issue is https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictions require an api key, when you use it inside a router child.

index.html

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&sensor=false"></script>

Put your google API key in place of API_KEY.

I cannot explain the difference in behavior between child component(no api key needed) and router child(api key required).

According to Google Map Api documentation, API key is required:

https://developers.google.com/maps/documentation/javascript/places-autocomplete

like image 94
John Siu Avatar answered Oct 25 '22 23:10

John Siu