Wednesday, 13 December 2017

Angular 2/4 routing with simple examples and share data using route.

Angular 4RoutingNavigateShare data

Here I am going to explain about implementing routing in Angular with simple examples. Angular team made routing so simple, let us check with some examples.

  1. Angular simple routing
  2. Navigate from component
  3. Pass data to component using route
  4. Nested routing

1. Angular routing


I going to create HomeComponent and FormComponent, clicking on Home/Form link it should navigate to the desired page/component. Check below image for understanding our simple folder structure.

Let us start with our Module code.

Module


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { FormComponent } from './form/form.component';
import { appRoutes } from './routing';

@NgModule({
    declarations: [
        AppComponent,
        HomeComponent,
        FormComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        RouterModule.forRoot(appRoutes)
    ],
    providers: [],
    bootstrap: [AppComponent]

})
export class AppModule { }

Here we have imported all the dependencies and appRoutes is our router file. Don't add appRoutes under declarations as it is not a component or pipe. If you add it under declarations angular will throw error.

AppComponent


import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    template: '<div>'
        + '<a routerLink="home" routerLinkActive="active">Home</a>'
        + '<a routerLink="form" routerLinkActive="active">Form</a>'
        + '<router-outlet></router-outlet>'
        + '</div>',
})

export class AppComponent {
    constructor() { }
}

Here <router-outlet></router-outlet> is angular representation for adding routing capabilities. Here I have used routerLinkActive, which will add active class on click. You can simply give some css for active class for highlighting the link on click. If you want to know more about adding class conditionally check these links: 5 different ways for conditionally adding class and Conditionally add class to an element on click.

Check below Router file code

Router


import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { FormComponent } from './form/form.component';

export const appRoutes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'form', component: FormComponent },
]

Here also we need to import the particular component and also import RouterModule and Routes. Before going for more details let me share HomeComponent and FormComponent code as well.

HomeComponent


import { Component } from '@angular/core';

@Component({
    selector: 'home',
    template: '<div>Home</div>'
})

export class HomeComponent {
    constructor() { };
}

FormComponent


import { Component } from '@angular/core';

@Component({
    selector: 'form',
    template: '<div>Form</div>'
})

export class FormComponent {
    constructor() { }
}

We are done. Click on the Home link it will navigate to http://localhost:4200/home and to http://localhost:4200/form on click of form link. If you want to redirect on some path initially you can add below code.


{ path: '', redirectTo: 'home', pathMatch: 'full' }

If user types some wrong url, you can force him navigate to some page. Check below code for that.


{ path: '**', redirectTo: 'home', pathMatch: 'full' }

If user types http://localhost:4200/hshshsshshsh ,then it will navigate to home page. Basically Angular team made routing so simple.

Check below complete router code


import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { FormComponent } from './form/form.component';

export const appRoutes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    { path: 'form', component: FormComponent },
    { path: '**', redirectTo: 'home', pathMatch: 'full' }
]

2. Navigate from component


Now let us check how we can navigate from component to another on some action. Let us check that with a simple example. I will be adding a button in the home page, on click of that it should navigate to form page.


import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    selector: 'home',
    template: '<div>Home : <button (click)="navigate();">Navigate to Form</button></div>'
})

export class HomeComponent {
    constructor(private router: Router) { }
    navigate() {
        this.router.navigate(['form']);
    }
}

We have used angular navigate method to achieve this.

3. Pass data to component using route.


Let us check how we can pass data to a component using route. I am adding some test data to our routing file. Check below code.


{ path: 'form', component: FormComponent ,data :{data :'Test Data'} },

We are passing data :{data :'Test Data'} to FormComponent on click on form link. We need to add some code in our FormComponent to receive this data.


import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
    selector: 'form',
    template: '<div>Form</div>'
})

export class FormComponent {
    sub: any;
    constructor(private route: ActivatedRoute) { }
    ngOnInit() {
        this.sub = this.route
            .data
            .subscribe(value => console.log(value));
    }
}

We are done. Don't forget to import ActivatedRoute. But remember this is not a preferred way to do this. Use parent child communication feature or make a service common to both component and share the data. There are other different ways to share data through routes check this link:- 3 simple ways to share data through routes.

4. Nested routing


Let us check how we can do nested routing. I will be creating two folder inside Form folder, aboutForm and contactForm. We will add two links to access this ichild components.

Updated Router


import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { FormComponent } from './form/form.component';
import { AboutFormComponent } from './Form/aboutForm/aboutform.component';
import { ContactFormComponent } from './Form/ContactForm/contactform.component';

export const appRoutes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    {
        path: 'form', component: FormComponent,
        children: [
            { path: '', component: AboutFormComponent },
            { path: 'about-form', component: AboutFormComponent },
            { path: 'contact-form', component: ContactFormComponent }
        ]
    },
    { path: '**', redirectTo: 'home', pathMatch: 'full' }
]

It is very simple, just add under children rest angular will take care. Don’t forget to import your new components into module. Now let us check FormComponent code.


import { Component } from '@angular/core';

@Component({
    selector: 'form',
    template: '<div>'
        + '<h4>Form</h4>'
        + '<a routerLink="about-form" routerLinkActive="active">About Form</a>'
        + '<a routerLink="contact-form" routerLinkActive="active">Contact Form</a>'
        + '<router-outlet></router-outlet>'
        + '</div>'
})

export class FormComponent {
    constructor() { }
}

Here you can notice that we added <router-outlet></router-outlet> and this is required. Click on Form it will navigate to Form page then you can select About Form or Contact Form link to access child components. Angular team made nested routing so simple. I will share AboutFormComponent and ContactFormComponent code as well below.


import { Component } from '@angular/core';

@Component({
    selector: 'about-form',
    template: '<div>About Form</div>'
})

export class AboutFormComponent {
    constructor() { }
}


import { Component } from '@angular/core';

@Component({
    selector: 'contact-form',
    template: '<div>Contact Form</div>'
})

export class ContactFormComponent {
    constructor() { }
}

In this article we have discussed about implementing a simple routing as well as nested routing using Angular and also about navigating from component itself.

Angular 4RoutingNavigateShare data

Related Info

1. Http calls in Angular with simple examples.

2. 5 different ways for conditionally adding class - Angular.

No comments :

Post a Comment