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

Using jQuery with Angular2 I know the idea of using jQuery with Angular2 may seen a little bit weird for lots of you, as we all know, Angular2 is responsible for managing everything related to our view components and DOM elements, it doesn't sound like a good idea to use another framework to do a job Angular can easily do. ...
Angular 2 Tutorial: Adding HotKeys (Keyboard shortcuts) to a Component Arguably hotkeys can substantially increase the usability of an application, the less the users have to touch the mouse the better will be their experience with the application. Luckily for us there is a very easy way of defining hotkeys on angular2, which is by adding a listener to the host comp...
Integrating an Angular2 app with a PHP app In this tutorial I'm going to show you how to use Angular2 Http client to communicate with an php application. I don't want this to be a very long post, so I'm going to make everything as simple as possible. The first step, of course, is to provide a php web service, it doesn't need to be anythin...
Passing Parameters to an Angular2 Component One of the greatest advantages of using components is reusability, which means once you've create your component you can use it in several places across your project without having to recreate it everytime. But for that to be possible we have to be able to pass parameters to our components, that's w...

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>