Angular 2 Routing With Nested Components Using Visual Studio IDE

Introduction

This article explains how to create multiple components and use routing concepts for navigating between the components. First, we will create the main component and then child components. Then, we will create multiple links which are used to navigate between the components with the help of Angular 2 routing.

Before jumping into creating the application, let's understand what Angular 2 component and routing are.

Component

Components are logical piece of code which are made up different pieces of information like templates, classes and metadata.

So, to keep it in simple words, they are like parts/regions/sections of your website.

Routing

Angular routing is the concept of navigating from one view to another view, so the user performs application tasks without reloading entire page.

Now, you have basic understanding on what Angular 2 Component and Routing are. Let’s start with creating a sample application to understand it better.

Prerequisites

  1. I will be using Visual Studio 2015 as my IDE to develop Angular 2 application in this article.
  2. Download the Angular seed project from here to start with Angular 2 application.
  3. Please go through the article, Separate TypeScript (TS) And JavaScript (JS) Files In Different Folders In Angular 2, as we will be using separate folders for TS and JS files.

Let’s start developing the sample application

  1. Create a new project and select empty template.



    Download the Angular seed project which I mentioned in prerequisites and copy the files into your project. Then, restore the packages defined in “package.json” file.

    Then, separate the TypeScript and JavaScript files by following the link provided under prerequisites.



    You can see project structure like the above screenshot once you have followed the steps defined in the prerequisites.

    The next step is to create components.

  2. Create Components

    The component created when we downloaded the seed project, will be used as the main component in this application. In our application, I will be creating four components and will use routing concepts to navigate between the components.

    Create a folder “First_Component” under “app” folder which holds our component file.



    Create a TypeScript file, name it as “first.component.ts”, and copy the following code.
    1. import  
    2. {  
    3.     Component  
    4. } from '@angular/core';  
    5.   
    6. @Component({  
    7.     selector: 'first-app',  
    8.     template: '<h1>This is First Component</h1>'  
    9. })  
    10. export class FirstComponent {}  


    In the similar way, try creating second component and add the following code.
    1. import {  
    2.     Component  
    3. } from '@angular/core';  
    4.   
    5. @Component({  
    6.     selector: 'second-app',  
    7.     template: '<h1>This is Second Component</h1>'  
    8. })  
    9. export class SecondComponent {}  


    Now, it’s time to create a third component. For the third component, we will create properties in the class with some sample text and bind the properties in the template.

    Add the following code after creating third component file.
    1. import {  
    2.     Component  
    3. } from '@angular/core';  
    4.   
    5. @Component({  
    6.     selector: 'third-app',  
    7.     template: '<h1>This is {{ComponentNumber}}rd {{SampleText}}</h1>'  
    8. })  
    9. export class ThirdComponent {  
    10.   
    11.     ComponentNumber: number = 3;  
    12.     SampleText: string = "Component";  
    13.   
    14. }  


    Our next task is to create a fourth component. This time, we will create an HTML file and access it using “templateUrl” instead of writing our HTML content as inline code. And also, we will add some style to the content using “styles” property.

    Create the fourth component in a similar way as we created the previous components and name it “fourth.component.ts”.

    We will add our component in Fourth_Component folder along with HTML file.



    Create an HTML file under “Fourth_Component” folder and name it “fourthcomponent.html”.



    Let’s add sample text in the HTML page.
    1. <h2>This is Fourth Component</h2>  
    2. <img src="http://lorempixel.com/g/400/200/" />   


    Refer the HTML page in the fourth component using templateUrl property under Component decorator and add some style to HTML content.

    Update the code in component.typescript file, as in the following.
    1. import {  
    2.     Component  
    3. } from '@angular/core';  
    4.   
    5. @Component({  
    6.     selector: 'fourth-app',  
    7.     templateUrl: './app/Fourth_Component/fourthcomponent.html',  
    8.     styles: ['h2 {color:green; }']  
    9. })  
    10. export class FourthComponent {}  
    Hey, congrats! You just created all four components which we discussed in the beginning of the article. Now, it’s time we work on Angular 2 routing to display the HTML content and navigate between the multiple components.

    Please cross check the files created and the project structure should look as below.



  3. Create Angular 2 Routing

    In order to navigate from one component to another component, we need to configure the routes for the components and we do it by creating a new TypeScript file.

    First, create base reference in “index,html” file by adding the following code under head tag.

    The <base href="/"> tells the Angular router how to compose navigation URLs. The router then only modifies the remaining part of the URL.



    Create a TypeScript file under “app” folder and name it “app.routes.ts”. Next, we need to import the Angular library which includes the necessary methods to configure the routing.
    1. import { Routes } from '@angular/router';   
    Next step is to import all the components we created, to define the route path.
    1. import { AppComponent } from './app.component';  
    2. import { FirstComponent } from './First_Component/first.component';  
    3. import { SecondComponent } from './Second_Component/second.component';  
    4. import { ThirdComponent } from './Third_Component/third.component';  
    5. import { FourthComponent } from './Fourth_Component/fourth.component';  
    Then, define the routes by creating a constant variable which holds the paths.
    1. export const routes: Routes = [  
    2. { path: 'First', component: FirstComponent },  
    3. { path: 'Second', component: SecondComponent },  
    4. { path: 'Third', component: ThirdComponent },  
    5. { path: 'Fourth', component: FourthComponent },  
    6.   
    7. ];  
    Congratulations! You have configured the routes. When you complete adding the code, this is how it should look.



    Now, let’s start creating the links in the main component to navigate between the components. Open “app.component.ts” file and change the code in template to include router links.
    1. <h1>My First Angular App</h1>  
    2. <a routerLink="First">First</a>  
    3. <a routerLink="Second">Second</a>  
    4. <a routerLink="Third">Third</a>  
    5. <a routerLink="Fourth">Fourth</a>  
    6. <br/>  
    7. <div>  
    8.     <router-outlet></router-outlet>  
    9. </div>  


    The paths that are configured in app.routes.ts are exported using constant “routes”. We need to import the route constants and all the components in our AppModule class.
    1. import { RouterModule } from '@angular/router';  
    2.   
    3. import { routes } from './app.routes';  
    4. import { FirstComponent } from './First_Component/first.component';  
    5. import { SecondComponent } from './Second_Component/second.component';  
    6. import { ThirdComponent } from './Third_Component/third.component';  
    7. import { FourthComponent } from './Fourth_Component/fourth.component';  
    Next, we will declare our components in our module in @NgModule decorator.
    1. imports: [ BrowserModule, RouterModule.forRoot(routes) ],  
    2.   
    3. declarations: [ AppComponent,FirstComponent,SecondComponent,ThirdComponent,FourthComponent ],  
    Our entire code in “app.module.ts” class should look like below
    1. import { NgModule } from '@angular/core';  
    2. import { BrowserModule } from '@angular/platform-browser';  
    3.   
    4. import { AppComponent } from './app.component';  
    5.   
    6. import { RouterModule } from '@angular/router';  
    7. import { FormsModule } from '@angular/forms';  
    8.   
    9. import { routes } from './app.routes';  
    10. import { FirstComponent } from './First_Component/first.component';  
    11. import { SecondComponent } from './Second_Component/second.component';  
    12. import { ThirdComponent } from './Third_Component/third.component';  
    13. import { FourthComponent } from './Fourth_Component/fourth.component';  
    14.   
    15. @NgModule({  
    16. imports: [BrowserModule, FormsModule,RouterModule.forRoot(routes)],  
    17. declarations: [ AppComponent,FirstComponent,SecondComponent,ThirdComponent,FourthComponent ],  
    18. bootstrap: [ AppComponent ]  
    19. })  
    20. export class AppModule { }  


    Run the application and you will see the output with multiple links on the page. You can navigate between the components by clicking on any of the links.


    Download the complete source code from any of the following links.

    GitHub
    (or)
    BitBucket

Thanks for reading. Hope it helps.

In case of any feedback or issue, please comment below.