Search code examples
angularroutesangular2-cli

How to declare default route in Angular2 CLI?


I made a small project using angular CLI but i don't know how to declare default route in CLI. I used '/' for parent component and it works but if i use '/' for child component it does not work.

My parent.component.ts is:

@Routes([
  { path: '/', component: LoginComponent },
])   

parent.component.html is:

<a [routerLink]="['/Login']"></a>
<router-outlet></router-outlet>

child.component.ts is:

@Routes([
    { path: '/', component: DashboardComponent},
])

child.component.html is:

<li class="treeview">
    <a [routerLink]="['']">Dashboard</a>
</li>
<router-outlet></router-outlet>

This method works with parent and child both but i want a route with another path e.g. "/dashboard" as default. Is there any way to define default route in child component.


Solution

  • i think you have to try this: -

    export const HomeRoutes: RouterConfig = [
        { path: '', redirectTo: '/home', terminal: true},
        { path: 'home', component: HomeComponent, terminal: true }
    ];
    

    PS:- Not Tested Credit to this answer

    update

    you also can try defining your route twice like this:-

    { path: '/', component: HomeComponent}
    { path: 'home', component: HomeComponent}
    

    by doing so there is default as well as named router for same component.

    hope may help you.