Seba Kerckhof
Seba Kerckhof

Reputation: 1391

How to delegate routes to a child component?

At the last angular-connect the component router 1.0 was shown and it had a feature where you could delegate a sub-tree of the routes to a certain component using two-dots notation. See: https://www.youtube.com/watch?v=z1NB-HG0ZH4&feature=youtu.be&t=720 .

I was a big fan of this feature as you could build a large component (e.g. a chat system) that needs its own routing, but have all of this encapsulated in the child component and therefore use it as a black-box wherever you wanted. This is a great feature for reusable components if you work in a large team.

In the router 3.0 this seems gone and instead you specify the child routes of a component inside nested arrays.

Does this mean you have to build your entire routing tree up-front and if you move components around, you need to change this tree manually? Does this mean you can't have a component with its own encapsulated routes? If I'm wrong, how is it done in the 3.0 router?

Upvotes: 2

Views: 391

Answers (3)

Rodinei Dias
Rodinei Dias

Reputation: 1

You can use it like this, in parent component:

@RouteConfig([
    {path: '/', component: HomeComponent, as: 'Home'},
    {path: '/list/...', component: ListComponent, as: 'List'}
])

And then in your ListComponent, define your child routes:

@RouteConfig([
  { path: '/:id', component: ListItem, as: 'ListItem' }
])

Make sure the ListComponent has a as well..

Upvotes: 0

Steve
Steve

Reputation: 1376

Your component routes are defined in a separate component route file, and then that file/object is imported into the main router. So they are still encapsulated, but moving around, repeating would require an additional import into the main router.

From the docs (about half way down, right above "Milestone #3":

https://angular.io/docs/ts/latest/guide/router.html

enter image description here

enter image description here

Upvotes: 0

maxisam
maxisam

Reputation: 22705

Does this mean you can't have a component with its own encapsulated routes?

Well, the router will not exist in component.ts file for sure, but you can put the part of routs in a service file under the same component folder and use relative path for your routes.

if you move components around, you need to change this tree manually?

you only need to change one route which is the one connect to that component. I think it doesn't really change a lot.

By using a separate route file, it allows us to lazy load components.

From doc

Defining configuration in a separate file paves the way for a future in which we load routing configuration immediately but delay loading the components themselves until the user needs them.

Such asynchronous routing can make our application launch more quickly. We'll cover asynchronous routing in a future chapter update.

Upvotes: 1

Related Questions