Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 routes for one Angular component

I'm wondering is it possible to have 2 different routes that point to 1 single component? For example:

{ path: 'signin', component: SignInComponent },
{ path: 'tenant/:id/signin', component: SignInComponent }

I'm asking because I have some wired behaviour..

like image 766
Vnuuk Avatar asked Dec 22 '16 06:12

Vnuuk


People also ask

Can we have multiple routes in Angular?

Angular Router supports multiple outlets in the same application. A component has one associated primary route and can have auxiliary routes. Auxiliary routes enable developers to navigate multiple routes at the same time.

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.

Can I use multiple router outlets in Angular 8?

This means that you will be able to access parameters and route information from multiple outlets simultaneously when using the Router service.

What are the two elements of routes in Angular?

The first property, path , is a string that specifies the URL path for the route. The second property, component , is a string that specifies what component your application should display for that path. From your code editor, open the app.


1 Answers

Yes you can use 2 different route that point to the same component. But when you navigate from a route to a different route that uses the same component as the previous route then angular reuses your component instance. It does not create a new instance of your component.

If you will navigate from 'signin' to 'tenant/:id/signin' then angular will use the same instance of SignInComponent that it created for 'signin'. The constructor and init methods of SignInComponent will not be called. You can use observable in your init method. The params method of ActivatedRoute is a observable. You can do something like this to extract the parameter:

route is your ActivatedRoute instance

ngOnInit() {
  this.route.params
    .switchMap((params: Params) => this.service.getHero(+params['id']))
    .subscribe((hero: Hero) => this.hero = hero);
}

The switchMap operator allows you to perform an action with the current value of the Observable, and map it to a new Observable. This code gets a hero with id specified in the route from the service. You can do something like this. If you will post the code then I can tell you what exactly you need to do.

like image 97
saurav1405 Avatar answered Oct 17 '22 04:10

saurav1405