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
- I will be using Visual Studio 2015 as my IDE to develop Angular 2 application in this article.
- Download the Angular seed project from here to start with Angular 2 application.
- 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
- 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.
- 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.
- import
- {
- Component
- } from '@angular/core';
-
- @Component({
- selector: 'first-app',
- template: '<h1>This is First Component</h1>'
- })
- export class FirstComponent {}
In the similar way, try creating second component and add the following code.
- import {
- Component
- } from '@angular/core';
-
- @Component({
- selector: 'second-app',
- template: '<h1>This is Second Component</h1>'
- })
- 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.
- import {
- Component
- } from '@angular/core';
-
- @Component({
- selector: 'third-app',
- template: '<h1>This is {{ComponentNumber}}rd {{SampleText}}</h1>'
- })
- export class ThirdComponent {
-
- ComponentNumber: number = 3;
- SampleText: string = "Component";
-
- }
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.
- <h2>This is Fourth Component</h2>
- <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.
- import {
- Component
- } from '@angular/core';
-
- @Component({
- selector: 'fourth-app',
- templateUrl: './app/Fourth_Component/fourthcomponent.html',
- styles: ['h2 {color:green; }']
- })
- 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.
- 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.
- import { Routes } from '@angular/router';
Next step is to import all the components we created, to define the route path.
- import { AppComponent } from './app.component';
- import { FirstComponent } from './First_Component/first.component';
- import { SecondComponent } from './Second_Component/second.component';
- import { ThirdComponent } from './Third_Component/third.component';
- import { FourthComponent } from './Fourth_Component/fourth.component';
Then, define the routes by creating a constant variable which holds the paths.
- export const routes: Routes = [
- { path: 'First', component: FirstComponent },
- { path: 'Second', component: SecondComponent },
- { path: 'Third', component: ThirdComponent },
- { path: 'Fourth', component: FourthComponent },
-
- ];
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.
- <h1>My First Angular App</h1>
- <a routerLink="First">First</a>
- <a routerLink="Second">Second</a>
- <a routerLink="Third">Third</a>
- <a routerLink="Fourth">Fourth</a>
- <br/>
- <div>
- <router-outlet></router-outlet>
- </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.
- import { RouterModule } from '@angular/router';
-
- import { routes } from './app.routes';
- import { FirstComponent } from './First_Component/first.component';
- import { SecondComponent } from './Second_Component/second.component';
- import { ThirdComponent } from './Third_Component/third.component';
- import { FourthComponent } from './Fourth_Component/fourth.component';
Next, we will declare our components in our module in @NgModule decorator.
- imports: [ BrowserModule, RouterModule.forRoot(routes) ],
-
- declarations: [ AppComponent,FirstComponent,SecondComponent,ThirdComponent,FourthComponent ],
Our entire code in “app.module.ts” class should look like below
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
-
- import { AppComponent } from './app.component';
-
- import { RouterModule } from '@angular/router';
- import { FormsModule } from '@angular/forms';
-
- import { routes } from './app.routes';
- import { FirstComponent } from './First_Component/first.component';
- import { SecondComponent } from './Second_Component/second.component';
- import { ThirdComponent } from './Third_Component/third.component';
- import { FourthComponent } from './Fourth_Component/fourth.component';
-
- @NgModule({
- imports: [BrowserModule, FormsModule,RouterModule.forRoot(routes)],
- declarations: [ AppComponent,FirstComponent,SecondComponent,ThirdComponent,FourthComponent ],
- bootstrap: [ AppComponent ]
- })
- 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.