title: Angular 4 div hidden vs ngIf render Agm Google Map API
body: <p>Im development a component using the AGM library with Angular 4.
  The component have 4 inputs:</p>
  
  <ul>
  <li>1º input: if variable "useGoogleMap" is false, then i show this input so the user can type a address without using google maps.</li>
  <li>2º input: AGM autocomplete input shows when variable "useGoogleMap" is true.</li>
  <li>3º &amp; 4º inputs: shows editable inputs for lat and lng that can be search on AGM map.</li>
  </ul>
  
  <p>The question is, if i use *ngIf="useGoogleMap" (and useGoogleMap = false), then AGM its not getting initialized, and when it comes useGoogleMap = true, the map its undefined to work with (ngOnInit, ngOnChanges, etc).</p>
  
  <p>I try hidden too, but hide or show its not automatic, only works with a blur() of some input at the component (don't know why).</p>
  
  <p>Here's some code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>export class InputGooglePlacesComponent implements OnInit, OnChanges {
    @ViewChild('googlePlaceInput') googlePlaceInputElementRef: ElementRef;
    @ViewChild('map') map: AgmMap;
    @ViewChild('marker') marker: AgmMarker;
    @ViewChild('useGoogle') useGoogle: ElementRef;
    @ViewChild('manualAddress') manualAddress: ElementRef;
  
    @Input() public label: string;
    @Input() public field: string;
    @Input() public placeholder = 'Escribe una dirección';
    @Input() public form: FormGroup;
  
    @Output() selectedPlace = new EventEmitter();
  
    @Input() public latitud: number = AppSettings.GMAPS_LOCATION_DEFAULT.lat;
    @Input() public longitud: number = AppSettings.GMAPS_LOCATION_DEFAULT.lng;
    @Input() public direccion: string = null;
  
    public finishChanges = new EventEmitter();
    private formatted_address: string;
    public zoom = 12;
    public autocomplete: any = null;
    public useGoogleMap = false;
  
    constructor(private mapsAPILoader: MapsAPILoader, private ngZone: NgZone) {}
  
    ngOnInit() {
      if (this.useGoogleMap) {
        this.loadPlaces();
      }
    }
  
    httpGet() {
      const url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + this.direccion.replace(/ /g, '+') + '&amp;key=' + AppSettings.GMAPS_API_KEY;
      const xmlHttp = new XMLHttpRequest();
      xmlHttp.open( "GET", url, false ); // false for synchronous request
      xmlHttp.send( null );
      return xmlHttp.response;
    }
  
  
    ngOnChanges(changeRecord: SimpleChanges) {
      if (this.useGoogleMap) {
      if (!this.latitud || !this.longitud) {
        if (this.direccion &amp;&amp; this.direccion !== '') {
          //No viene la latitud o longitud, y la dirección viene por BD. Se setea como dirección manual.
          this.manualAddress.nativeElement.value = this.direccion;
          this.useGoogleMapAPI(false);
        } else {
          //No viene ninguno de los 3 campos (lat, lng, dirección). Se setea direccion gmap por defecto.
          this.latitud = AppSettings.GMAPS_LOCATION_DEFAULT.lat;
          this.longitud = AppSettings.GMAPS_LOCATION_DEFAULT.lng;
          this.zoom = 9;
  
          this.mapsAPILoader.load().then(() =&gt; {
  
            let latlng;
            latlng = new google.maps.LatLng(this.latitud, this.longitud);
  
            new google.maps.Geocoder().geocode({ location: latlng }, (results, status) =&gt; {
              if (status === google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                  this.formatted_address = results[0].formatted_address;
                }
  
                this.selectedPlace.emit({
                  formatted_address: this.formatted_address,
                  latitud: this.latitud,
                  longitud: this.longitud,
                  coordinates: `POINT(${this.longitud} ${this.latitud})`
                });
              }
            });
  
            this.useGoogleMapAPI(true);
            this.map.triggerResize();
          });
  
        }
      } else {
        if (this.direccion &amp;&amp; this.direccion !== '') {
          this.mapsAPILoader.load().then(() =&gt; {
            const location = JSON.parse(this.httpGet()).results[0];
  
            const latitud = Math.round(Math.abs(this.latitud) * 1000000) / 1000000;
            const geolatitud = Math.round(Math.abs(location.geometry.location.lat) * 1000000) / 1000000;
  
            const longitud = Math.round(Math.abs(this.longitud) * 1000000) / 1000000;
            const geolongitud = Math.round(Math.abs(location.geometry.location.lng) * 1000000) / 1000000;
  
            if ( Math.abs(latitud - geolatitud) &lt;= 0.001 &amp;&amp; Math.abs(longitud - geolongitud) &lt;= 0.001) {
              //Coincide la dirección con la georeferencia
              this.initMarkerObservable({ coords: { lat: this.latitud, lng: this.longitud } }).subscribe(() =&gt; {
                this.finishChanges.emit();
              });
              this.zoom = 12;
              this.useGoogleMapAPI(true);
              this.map.triggerResize();
            } else {
              //No coincide la dirección con la georeferencia
  
              // this.latitud = null;
              // this.longitud = null;
  
              this.manualAddress.nativeElement.value = this.direccion;
              this.manualAddress.nativeElement.blur();
              this.useGoogleMapAPI(false);
            }
          });
        } else {
          this.latitud = AppSettings.GMAPS_LOCATION_DEFAULT.lat;
          this.longitud = AppSettings.GMAPS_LOCATION_DEFAULT.lng;
          this.zoom = 9;
  
          this.mapsAPILoader.load().then(() =&gt; {
  
            let latlng;
            latlng = new google.maps.LatLng(this.latitud, this.longitud);
  
            new google.maps.Geocoder().geocode({ location: latlng }, (results, status) =&gt; {
              if (status === google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                  this.formatted_address = results[0].formatted_address;
                }
  
                this.selectedPlace.emit({
                  formatted_address: this.formatted_address,
                  latitud: this.latitud,
                  longitud: this.longitud,
                  coordinates: `POINT(${this.longitud} ${this.latitud})`
                });
              }
            });
  
            this.useGoogleMapAPI(true);
            this.map.triggerResize();
          });
        }
      }
    }
    }
  
    loadPlaces() {
      this.mapsAPILoader.load().then(() =&gt; {
        this. autocomplete = new google.maps.places.Autocomplete(this.googlePlaceInputElementRef.nativeElement, {
          types: ['address']
        });
  
        this.autocomplete.addListener('place_changed', () =&gt; {
          this.ngZone.run(() =&gt; {
            const place: google.maps.places.PlaceResult = this.autocomplete.getPlace();
            if (place.geometry === undefined || place.geometry === null) {
              return;
            }
            this.latitud = place.geometry.location.lat();
            this.longitud = place.geometry.location.lng();
  
            this.selectedPlace.emit({
              formatted_address: place.formatted_address,
              latitud: place.geometry.location.lat(),
              longitud: place.geometry.location.lng(),
              coordinates: `POINT(${place.geometry.location.lng()} ${place.geometry.location.lat()})`
            });
          });
        });
      });
    }
  
    clickMarker(event: any) {
      if (this.useGoogleMap) {
      this.latitud = event.coords.lat;
      this.longitud = event.coords.lng;
  
      let latlng;
      latlng = new google.maps.LatLng(this.latitud, this.longitud);
  
      new google.maps.Geocoder().geocode({ location: latlng }, (results, status) =&gt; {
        if (status === google.maps.GeocoderStatus.OK) {
          if (results[0]) {
            this.formatted_address = results[0].formatted_address;
          }
  
          this.selectedPlace.emit({
            formatted_address: this.formatted_address,
            latitud: this.latitud,
            longitud: this.longitud,
            coordinates: `POINT(${this.longitud} ${this.latitud})`
          });
        }
      });
    }
    }
  
    initMarkerObservable(event: any): Observable&lt;any&gt; {
      if (this.useGoogleMap) {
        return new Observable&lt;any&gt;(observer =&gt; {
          this.latitud = event.coords.lat;
          this.longitud = event.coords.lng;
  
          let latlng;
          latlng = new google.maps.LatLng(this.latitud, this.longitud);
  
          const promise = new Promise((resolve, reject) =&gt; {
            new google.maps.Geocoder().geocode({ location: latlng }, (results, status) =&gt; {
              if (status === google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                  this.formatted_address = results[0].formatted_address;
                }
  
                this.selectedPlace.emit({
                  formatted_address: this.formatted_address,
                  latitud: this.latitud,
                  longitud: this.longitud,
                  coordinates: `POINT(${this.longitud} ${this.latitud})`
                });
  
                resolve();
              }
            });
          }).then(() =&gt; {
            observer.next('');
            observer.complete();
          });
        });
      }
    }
  
    triggerResize() {
      if (this.useGoogleMap) {
        this.map.triggerResize();
      }
    }
  
    resetPlaces() {
      if (this.useGoogleMap) {
        this.googlePlaceInputElementRef.nativeElement.value = '';
      }
    }
  
  
    setUseGoogle() {
      this.useGoogleMap = this.useGoogle.nativeElement.checked;
      if (this.useGoogleMap) {
        this.loadPlaces();
        this.map.triggerResize();
      }
    }
  
    useGoogleMapAPI(checked: boolean) {
      this.useGoogle.nativeElement.checked = checked;
      this.setUseGoogle();
    }
  
    recalculatePosition(event: any) {
      if (this.useGoogleMap) {
        if (event.srcElement.id === 'mapLatitud') {
          this.latitud = Number(event.srcElement.value);
        } else if (event.srcElement.id === 'mapLongitud') {
          this.longitud = Number(event.srcElement.value);
        }
        this.clickMarker({ coords: { lat: this.latitud, lng: this.longitud } });
      }
    }
  }</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>agm-map {
      height: 300px;
  }
  .coords__input {
      margin: 10px 0;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="form-group" [formGroup]="form"&gt;
      &lt;div class="row"&gt;
          &lt;div class="col-md-6"&gt;&lt;label [for]="field"&gt;{{ label }}&lt;/label&gt;&lt;/div&gt;
          &lt;div class="col-md-6"&gt;&lt;label for="useGoogle" &gt;&lt;input id="useGoogle" type="checkbox" (change)="setUseGoogle()" #useGoogle/&gt;&amp;nbsp;Usar google maps&lt;/label&gt;&lt;/div&gt;
      &lt;/div&gt;
  
      &lt;div *ngIf="!useGoogleMap"&gt;
        &lt;input [type]="text" class="form-control form-control-sm"
               [id]="field" [placeholder]="placeholder"
               [autocapitalize]="autocapitalize" [spellcheck]="spellcheck" #manualAddress&gt;
      &lt;/div&gt;
  
      &lt;div *ngIf="useGoogleMap"&gt;
        &lt;input
            [id]="field" [placeholder]="placeholder" [formControlName]="field"
            type="text"
            class="form-control form-control-sm"
            #googlePlaceInput /&gt;
        &lt;div class="row"&gt;
          &lt;div class="col-md-6"&gt;
            &lt;input id="mapLatitud" type="number" class="form-control form-control-sm coords__input" [value]="latitud" (blur)="recalculatePosition($event)"/&gt;
          &lt;/div&gt;
          &lt;div class="col-md-6"&gt;
            &lt;input id="mapLongitud" type="number" class="form-control form-control-sm coords__input" [value]="longitud" (blur)="recalculatePosition($event)"/&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;agm-map
            [usePanning]="true"
            [latitude]="latitud"
            [longitude]="longitud"
            [zoom]="zoom"
            (mapClick)=clickMarker($event) #map&gt;
            &lt;agm-marker [latitude]="latitud" [longitude]="longitud" #marker&gt;
            &lt;/agm-marker&gt;
        &lt;/agm-map&gt;
        &lt;app-form-control-errors [form]="form" [field]="field" [singleInput]="googlePlaceInput"&gt;
        &lt;/app-form-control-errors&gt;
  
      &lt;/div&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>I hope somebody can help me.
  I will be updating any progress.</p>