Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 router (@angular/router), how to set default route?

Tags:

angular

How can I set a default route in my @Routes route metadata collection? If you use the angular2 router from @angular/router-deprecated you define the routes in @routeConfig object, which is a collection of route objects, but these route objects have more attributes on them. For instance they have 'name' and 'useAsDefualt' attributes whereas the routes defined out of @angular/router do not. I would like to write my new app using the new router, but how do i use the new router and set a default route?

This is my main app component which defines my routes:

import { Component } from '@angular/core';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ConfigManagerComponent } from './configManager/configManager.component';
import { ApplicationMgmtComponent } from './applicationMgmt/applicationMgmt.component';
import { MergeComponent } from './merge/merge.component';

import { ROUTER_DIRECTIVES, Routes } from '@angular/router';


@Component({
    selector: 'app-container',
    templateUrl: 'app/app.component.html',
    directives: [ROUTER_DIRECTIVES]
})

@Routes([

        { path: '/Dashboard', component: DashboardComponent },
        { path: '/ConfigManager', component: ConfigManagerComponent },
        { path: '/Merge', component: MergeComponent },
        { path: '/ApplicationManagement', component: ApplicationMgmtComponent }
])

export class AppComponent { }

The route definitions seem to be working fine, when I click on anchor tags like this one:

<li class="nav hidden-xs"><a [routerLink]="['./Dashboard']">Dashboard</a>/li>

It transitions to the associated route. My only issue is that when my app loads it doesn't have a route active. How do i define a default route that is active when my app bootstraps?

Thanks!

like image 610
cobolstinks Avatar asked Jun 03 '16 02:06

cobolstinks


People also ask

What is default routing in Angular?

Default is "/" (the root path). The path-matching strategy, one of 'prefix' or 'full'. Default is 'prefix'. By default, the router checks URL elements from the left to see if the URL matches a given path and stops when there is a config match.

What is the correct way to add a basic route in Angular?

First, add links to the two components. Assign the anchor tag that you want to add the route to the routerLink attribute. Set the value of the attribute to the component to show when a user clicks on each link. Next, update your component template to include <router-outlet> .

What is angular2 routing?

Routing helps in directing users to different pages based on the option they choose on the main page. Hence, based on the option they choose, the required Angular Component will be rendered to the user. Let's see the necessary steps to see how we can implement routing in an Angular 2 application.

How does Angular determine routing change?

Steps to detect route change in Angular application Urls. Import Router, Event, NavigationStart, NavigationEnd, NavigationError from '@angular/router'. And inject router in the constructor. Subscribe to the NavigationStart, NavigationEnd, NavigationError events of the router.


10 Answers

V2.0.0 and later

See also see https://angular.io/guide/router#the-default-route-to-heroes

RouterConfig = [
  { path: '', redirectTo: '/heroes', pathMatch: 'full' },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '', redirectTo: '/detail', pathMatch: 'full' },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

There is also the catch-all route

{ path: '**', redirectTo: '/heroes', pathMatch: 'full' },

which redirects "invalid" urls.

V3-alpha (vladivostok)

Use path / and redirectTo

RouterConfig = [
  { path: '/', redirectTo: 'heroes', terminal: true },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '/', redirectTo: 'detail', terminal: true },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

RC.1 @angular/router

The RC router doesn't yet support useAsDefault. As a workaround you can navigate explicitely.

In the root component

export class AppComponent {
  constructor(router:Router) {
    router.navigate(['/Merge']);
  }
}

for other components

export class OtherComponent {
  constructor(private router:Router) {}

  routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree, prevTree?: RouteTree) : void {
    this.router.navigate(['SomeRoute'], curr);
  }
}
like image 147
Günter Zöchbauer Avatar answered Oct 12 '22 02:10

Günter Zöchbauer


You set path of route is ''. Example for DashboardComponent is load first.

@Routes([
        { path: '', component: DashboardComponent },
        { path: '/ConfigManager', component: ConfigManagerComponent },
        { path: '/Merge', component: MergeComponent },
        { path: '/ApplicationManagement', component: ApplicationMgmtComponent }
])

Hope it help you.

like image 44
Nguyen Avatar answered Oct 12 '22 02:10

Nguyen


In Angular 2+, you can set route to default page by adding this route to your route module. In this case login is my target route for the default page.

{path:'',redirectTo:'login', pathMatch: 'full' },
like image 23
Hiran Avatar answered Oct 12 '22 02:10

Hiran


according to documentation you should just

{ path: '**', component: DefaultLayoutComponent }

on your app-routing.module.ts source: https://angular.io/guide/router

like image 35
Eddy Ferreira Avatar answered Oct 12 '22 02:10

Eddy Ferreira


I faced same issue apply all possible solution but finally this solve my problem

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}

Hope this will help you.

like image 40
Jayant Patil Avatar answered Oct 12 '22 02:10

Jayant Patil


Suppose you want to load RegistrationComponent on load and then ConfirmationComponent on some event click on RegistrationComponent.

So in appModule.ts, you can write like this.

RouterModule.forRoot([
      { 
        path: '', 
        redirectTo: 'registration', 
        pathMatch: 'full'
       },
       { 
        path: 'registration', 
        component: RegistrationComponent
       },
      {
        path : 'confirmation',
        component: ConfirmationComponent
      }
    ]) 

OR

RouterModule.forRoot([
       { 
        path: '', 
        component: RegistrationComponent
       },
      {
        path : 'confirmation',
        component: ConfirmationComponent
      }
    ]) 

is also fine. Choose whatever you like.

like image 45
Alok Ranjan Avatar answered Oct 12 '22 00:10

Alok Ranjan


The path should be left blank to make it default component.

{ path: '', component: DashboardComponent },
like image 38
Bimal Kharel Avatar answered Oct 12 '22 00:10

Bimal Kharel


I just faced the same issue, I managed to make it work on my machine, however the change I did is not the same way it is mentioned in the documentation so it could be an issue of angular version routing module, mine is Angular 7

It only worked when I changed the lazy module main route entry path with same path as configured at the app-routes.ts

routes = [{path:'', redirectTo: '\home\default', pathMatch: 'full'},
           {path: '', 
           children: [{
             path:'home',
             loadChildren :'lazy module path'      
           }]

         }];

 routes configured at HomeModule
 const routes = [{path: 'home', redirectTo: 'default', pathMatch: 'full'},
             {path: 'default', component: MyPageComponent},
            ]

 instead of 
 const routes = [{path: '', redirectTo: 'default', pathMatch: 'full'},
                   {path: 'default', component: MyPageComponent},
                ]
like image 43
Sameh Avatar answered Oct 12 '22 02:10

Sameh


With the current version of angular 2 you can't use '/' on a path or give a name to your route. What you can do is create a route file like "app.routes.ts" and import your components, make sure of the path when importing.

import { Component } from '@angular/core';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ConfigManagerComponent } from './configManager/configManager.component';
import { ApplicationMgmtComponent } from './applicationMgmt/applicationMgmt.component';
import { MergeComponent } from './merge/merge.component';`

Add:

import {RouterConfig, provideRouter } from '@angular/router';

Then your routes:

const routes:RouterConfig = [      
    { path: 'Dashboard', component: DashboardComponent },
    { path: 'ConfigManager', component: ConfigManagerComponent },
    { path: 'Merge', component: MergeComponent },
    { path: 'ApplicationManagement', component: ApplicationMgmtComponent }
 ];

Then export:

export  const APP_ROUTER_PROVIDERS = [
    provideRouter(routes)]

In your main.ts import APP_ROUTER_PROVIDERS and add bootstrap the router providers to the main.ts like this:

bootstrap(AppComponent,[APP_ROUTER_PROVIDERS]);

Finally, your link will look like this:

li class="nav hidden-xs"><a [routerLink]="['./Dashboard']" routerLinkActive="active">Dashboard</a>/li>
like image 31
user6569033 Avatar answered Oct 12 '22 01:10

user6569033


Only you need to add other parameter in your route, the parameter is useAsDefault:true. For example, if you want the DashboardComponent as default you need to do this:

@RouteConfig([
    { path: '/Dashboard', component: DashboardComponent , useAsDefault:true},
    .
    .
    .
    ])

I recomend you to add names to your routes.

{ path: '/Dashboard',name:'Dashboard', component: DashboardComponent , useAsDefault:true}
like image 34
ernesto petit Avatar answered Oct 12 '22 00:10

ernesto petit