Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular route to same component with different parameters

Tags:

angular

I have a component that can route to itself but with different route parameters.

As you probably know this wont fire the constructor or ngOnInit.

To get around this I have the following in my constructor

this.router.routeReuseStrategy.shouldReuseRoute = function () {
    return false;
}

This solve the problem but I realize that my routes go crazy when using it. For instance a link to a totally different route becomes active and when I hover over it, it seems to have changed from the url it should be to the current URL. (hard to describe)

like image 589
Nico Avatar asked Aug 13 '18 15:08

Nico


People also ask

Can we have multiple routes in Angular?

Auxiliary routes allow you to use and navigate multiple routes. To define an auxiliary route you need a named router outlet where the component of the auxiliary route will be rendered. Since we are using an empty path, the sidebar component will be rendered when our application is started.

Can we use 2 router outlet in Angular?

You can have multiple router-outlet in same template by configuring your router and providing name to your router-outlet, you can achieve this as follows. Advantage of below approach is thats you can avoid dirty looking URL with it. eg: /home(aux:login) etc.

What is difference between routerLink and routerLink?

What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.


1 Answers

I'd suggest an alternative approach - overriding the Angular routing logic is likely to be error prone (as you've already discovered), and I'm fairly sure that you should be able to achieve what you're after in other, simpler ways.

One way would be writing a setup method that you can call when you need to setup (or reset) your component and then subscribing to the params observable on the ActivatedRoute, using that event to call your setup method - like this:

import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent {

  setupMessage = 'not set up yet';
  someParameterValue = null;

  constructor(private activateRoute: ActivatedRoute) {
    activateRoute.params.subscribe(params => {
      this.setupComponent(params['someParam']);
    })
  }

  setupComponent(someParam) {
    this.setupMessage = 'set up at ' + new Date();
    this.someParameterValue = someParam;
  }
}

Here is a working stackblitz demo of this.

like image 101
Steve Land Avatar answered Jan 03 '23 21:01

Steve Land