Ironmantra
Ironmantra

Reputation: 25

Angular 2 routing that triggers new component instantiation or event trigger I can hook into

my Angular 2 site has a nav bar in the left column, and I want to update a list of items in middle column (via webapi call) when user selects from nav bar. I want the selected nav item to be highlighted reflecting the users choice, the browser url to be updated etc. when user selects a nav bar item. Everything works as expected on the first selection using OnInit event, but not on subsequent selections even though the url in the browser updates. I need a way to tell the "groupItems" component to redraw with the latest groupId. Attempts to use other Angular lifecycle events haven't been successful. How should I be approaching this? Subsequent nav bar clicks reuse existing instance. My understanding is that there is a way to trigger a new instance of "groupItems" on each nav bar click as my current code is telling the dependency injector to reuse the same instance on each nav bar click. I've tried using a click event handler that updates a public property in the child (middle) component but I don't get the navigation behavior I want (browser url, history) using that approach, not to mention that the selected group isn't left selected in nav bar. Yes I could tweak the style to highlight the selection, but I'm ramping up on Angular 2 and am asking this question for guidance on whether the "routerLink" approach I'm using has any chance of working or if there is a completely different approach I should be taking.

<ul class='nav navbar-nav' >
   <li *ngFor="let group of groups" [routerLinkActive]="['link-active']">
       <a [routerLink]="['groupItems', group.groupId]">
            <span>{{group.keyword}}</span>
       </a>
   </li>
</ul>

Upvotes: 0

Views: 492

Answers (1)

DeborahK
DeborahK

Reputation: 60596

You can subscribe to the route parameters in the component. That way each time the group id changes, the code will update. Here is an example:

import { ActivatedRoute } from '@angular/router';
...
   constructor(private route: ActivatedRoute) {
      this.route.paramMap.subscribe(
         params => {
            console.log(params.get('id'));
         }
      );
   }

Instead of simply logging the new parameter, you can provide the code to refresh the data.

You can find out more about routing here: https://app.pluralsight.com/library/courses/angular-routing/table-of-contents

Upvotes: 1

Related Questions