hGen
hGen

Reputation: 2285

Angular OnInit not triggered after routing to component

I just ran into a very weird problem I've never had with the angular router before.

I'm using a leaflet plugin to display some map markers related to my underlying dataset. In order to get to more detail information about these places a click on one of the markers should route the user to another component called detail by passing the respective dataset id within the url (detail/:id).

However, in this case the component is loaded and the constructor is called, but the implemented OnInit function is not triggered as normally. There's just nothing happening there.

All this can also be seen in this stackblitz example.

Is this a known bug in the current release of Angular (6.0.5)? If so, is there a workaround?

Cheers and thanks in advance

Upvotes: 1

Views: 1893

Answers (1)

cezn
cezn

Reputation: 3055

Clicking on marker runs logic outside of NgZone which prevents change detection from happening. You need to run it manually. Inject NgZone into MapComponent

export class MapComponent {
...
  constructor(private router: Router, private ngZone: NgZone) {...}

Then change

 marker_label.on('click', (event: MouseEvent) => {
            const link = ['detail', id];
            this.router.navigate(link);
        });

to

marker_label.on('click', (event: MouseEvent) => {
            const link = ['detail', id];
            this.ngZone.run(() => this.router.navigate(link))
        });

Upvotes: 6

Related Questions