5

Let's say I'm at the Tab1 with the parameter id=1. Concretely the resulting url is http://localhost:4200/project/tab1;id=1. Now I click Tab2 and the url changes to http://localhost:4200/project/tab2. Is there a way to route the id too so that I get http://localhost:4200/project/tab2;id=1?

https://stackblitz.com/edit/angular-qzwzju

<nav mat-tab-nav-bar [backgroundColor]="'primary'">
    <div mat-tab-link *ngFor="let link of navTabs" [routerLink]="link.link" routerLinkActive #rla="routerLinkActive"
      [active]="rla.isActive">
      {{link.label}}
    </div>
</nav>
<router-outlet></router-outlet>
navTabs: NavTab[];

activeLinkIndex: number = -1;

constructor(private router: Router, private route: ActivatedRoute) {
  this.navTabs = [
    { label: 'Tab1', link: './tab1', index: 0 },
    { label: 'Tab2', link: './tab2', index: 1 },
    { label: 'Tab3', link: './tab3', index: 2 },
  ];
}

ngOnInit(): void {   
  this.router.events.subscribe((res) => {
    this.activeLinkIndex = this.navTabs.indexOf(this.navTabs.find((tab: NavTab) => tab.link === '.' + this.router.url));
  });
}
export const appRoutes: Routes = [
  { path: 'tab1', component: Tab1Component },
  { path: 'tab2', component: Tab2Component },
  { path: 'tab3', component: Tab3Component },
];
metidon776
  • 51
  • 1
  • 3

1 Answers1

0

You can do this by setting the state on the router.

Example: (this.router is Router)

// In TypeScript
this.router.navigate(['/tab1'], {state: {something: 1}});

or

// In HTML
<a [routerLink]=”/tab1” [state]=”{ something: 1}”>Go to B</a>

Then, in your target component, you can retrieve the value from the state by:

this.router.getCurrentNavigation().extras.state.something

You may need to subscribe to the router events and wait for NavigationEnd if you find it too noisy.

Another option is to just grab it from history.state.data. I'd argue that this isn't "the angular way" but it works.

Other options are:

  • use a NavigationResolver
  • Implement a State Machine like NgRx
  • Create a Service and use an EventEmitter to broadcast the id to any other components that might want to know about it.
mwilson
  • 12,295
  • 7
  • 55
  • 95
  • Where should I use this.router.navigate? The nav tabs don't use this to navigate to the specifc tab url. Can you show a stackblitz demo? – metidon776 Mar 08 '20 at 11:59
  • Then I would use the `[routerLink]` with the `[state]` directives in your html template. Whether you do it in TypeScript or within your HTML makes no differnce. – mwilson Mar 08 '20 at 19:30