Tutorial: How to redirect in Angular2

In this tutorial I’m going to give you a very simple example of how to navigate between components on an Angular2 application, but before we begin there are some configurations we have to do.

We’re going to use 2 components in this example: Component1 and Component2, to be able to redirect and navigate from one to the other we’re going to use the RouterModule, and for that module to work we have to create a file called app.routing.ts:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Component1 } from './component1.component';
import { Component2 } from './component2.component';
 
const appRoutes: Routes = [
  { path: 'component1', component: Component1 },
  { path: 'component2', component: Component2 }
];
 
export const appRoutingProviders: any[] = [];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

This is the file where we can define the routes, it allows us to specify a path for each of our components, as you can see in the code I’ve defined the paths /component1 and /component2 which will allow me to redirect to both my components.

Next we have to import the routing configuration on the app.module.ts as follows:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { routing, appRoutingProviders }  from './app.routing';
import { Component1 } from './component1.component';
import { Component2 } from './component2.component';
 
@NgModule({
  imports:      [ BrowserModule, routing ],
  declarations: [ AppComponent, Component1, Component2],
  providers:    [appRoutingProviders],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Perfect! We’re done with the configurations, now you can redirect by passing the path to the routerLink attribute of a regular link:

<a routerLink="/component1" >Component 1</a>
<a routerLink="/component2" >Component 2</a>

This will have the same effect as typing http://localhost:3000/component1 on the browser.

Recommended for you

Creating an Angular2 Image Gallery In order to make this tutorial easier for beginners I'm going to start by creating the simplest possible gallery, from there I'm going to develop and add more functionalities to it, which will increasingly make the gallery more complex as we proceed. If you are already familiar and have some experie...
Angular2 Forms Tutorial: Creating Custom Validators Every now and then developers come across situations where existing validators are not suitable for their needs, if you are facing this situation your best option is to create a custom validatior, to illustrate how you can do that in angular2 I'm going to create a simple custom validator that will v...
Angular2: How to Sort a JSON Dataset by Field To be able to sort an array we don't need anything specific from angular2, it can be accomplished just by using regular javascript, more specifically, we have to use the function sort() from the Array object, let's see an example: someArray.sort(function(a, b){ if ( a.someField < b.someFi...
Angular2 Error: No base href set. Please provide a value for the APP_BASE_HREF token or add a base e... This is a very common error for Angular2 beginners, if you are reading this it's probably because you're using the RouterModule module for the first time, you've done everything right but when you run your application you see something like this on your firebug: core.umd.js:3462 EXCEPTION: No b...

One comment on “Tutorial: How to redirect in Angular2

  1. namita jain

    Hi,

    I want to redirect to another component if login credentials are correct else redirect to same page.

    import { Component } from '@angular/core';
    import { Hero }    from './hero';
    import { Routes, RouterModule,RouterConfig } from '@angular/router';
    import { HomeComponent } from 'app/home.component';
     
    @RouterConfig([
      { path: '/home',  component: HomeComponent,  name: 'home' }
      ])
     
    @Component({
      selector: 'login-form',
      templateUrl: 'app/login-form.component.html'
      providers: [ROUTER_PROVIDERS]
    })
     
     
    export class AppComponent {
    active = true;
    model = new Hero('', '');
      checkValid(model){
        var userid = localStorage.getItem('name');
        var password = localStorage.getItem('password');
        if((userid == model.name1) &amp;&amp; (password == model.password1)) {
            alert("Welcome User");
           this.router.navigate(['/home']);
     
        }
        else {
     
            model.name1 = '';
            model.password1 = '';
            alert("You are not valid User");
          }
      } }

    This is my code, its not working properly

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>