Search code examples
angularapolloangular2-changedetectionngoninit

angular 2+ ngIf div not appearing except after clicking on page


I have Google maps on the home page and I'm trying to route the user to another page when closing the info window that appears on the map:

// Google map info window code snippet from a @Directive
infowindow.addListener('closeclick', () => {
  this.router.navigate(['/users', user.id]);
});

// Component code
ngOnInit() {
  this.user$ = this.route.params.switchMap((params: Params) => this.service.getUser(params['id']));
}

// UserService
getUser(id: String): Observable < User > {
  return this.apollo.watchQuery < GetUserQueryResult > ({
    query: GetUserQuery,
    variables: {
      id: id
    }
  }).map(({
    data
  }) => data.User);
}
<div *ngIf="user$ | async as user" class="container">
  <p>user.name</p>
</div>

The problem is that when I get to the user page, the div never gets displayed except when actually click on the page once. What's wrong?


Solution

  • Running handler code inside angular zone should help you

    import { NgZone } from '@angular/core';
    
    ...
    constructor(private zone: NgZone) {}
    
    infowindow.addListener('closeclick', () => {
      this.zone.run(() => this.router.navigate(['/users', user.id]));
    });
    

    See also