Author avatar

Parul Saxena

Displaying Routed Content with routerOutlet in Angular

Parul Saxena

  • Jun 26, 2020
  • 9 Min read
  • 263 Views
  • Jun 26, 2020
  • 9 Min read
  • 263 Views
Languages Frameworks and Tools
Front End Web Developer
Client-side Frameworks
Angular

Introduction

Angular is a single-page application development framework. In a single-page application, only one HTML page is rendered to the end-user, and that one page has a placeholder element in which HTML for all different routes of the application is rendered and shown to the end-user. This placeholder element is called the router-outlet. The single page that is rendered on the first load of the application never takes a round trip back to the server. In this guide, you will learn how to use a router-outlet to render the output of different routes to the end-user. You will create a demo application having a navigation bar with links to two routes of the application.

To complete this guide, you must have the following:

  1. Node - 12.17.0
  2. Angular CLI - 9.0.2
  3. Visual Studio Code - 1.45.1

Getting Started

Creating an Angular Project

  1. Execute the following command to create an Angular project.

ng new router-outlet-demo

  1. When prompted to add routing to the application, press 'N'.
  2. When prompted to choose stylesheet format, press 'ENTER'.

Opening the Generated Application in Visual Studio Code

  1. Click on the File menu in the top menu bar and select the menu option Open Folder.
  2. In the file dialog box, navigate to the folder where you generated the application.
  3. In this folder, you should see a folder named router-outlet-demo. Select this folder and click Open in the file dialog box.

Setting up the Project

The next step is to install Twitter Bootstrap and jQuery and reference them in the project so you can use some of the form styles to make the form look good.

  1. Go to the command prompt and run the following command:

cd router-outlet-demo

  1. Run the following command to install jquery:

npm i jquery

  1. Run the following command to install Bootstrap:

npm i bootstrap

  1. In Visual Studio Code, open the file angular.json.
  2. Add the following line in the styles array before src/style.css.

"node_modules/bootstrap/dist/css/bootstrap.min.css",

  1. Add the following lines in the scripts array:

"node_modules/jquery/dist/jquery.min.js", "node_modules/bootstrap/dist/js/bootstrap.min.js"

  1. In Visual Studio Code, open the file src > index.html.
  2. At line number 10 of the body element, add the following class:

class="container"

The final code should look like this:

1
2
3
<body class="container">
  <app-root></app-root>
</body>

Now the project is all set to develop the routing. 

Setting up the Routing

In Visual Studio Code, open the file src > app > app.module.ts, delete the existing content, and add the following code. This code imports Angular's router module and creates a routes array in which you will keep all your application routes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { NavBarComponent } from './nav-bar/nav-bar.component';
import {RouterModule, Routes} from '@angular/router';

const routes: Routes = [
];

@NgModule({
  declarations: [
    AppComponent,
    NavBarComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Developing the Home Component

  1. Run the following command in the command prompt:

ng generate component home

  1. In Visual Studio Code, open the file src > app > home > home.component.html, delete the existing content, and add following code:
1
2
3
4
5
6
7
8
9
10
11
<h1>Home Component</h1>
<pre>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Aliquam sem fringilla ut morbi tincidunt. Feugiat nibh sed pulvinar proin gravida hendrerit. Sed blandit libero volutpat sed cras ornare. 
Est lorem ipsum dolor sit amet consectetur adipiscing. Bibendum at varius vel pharetra vel turpis nunc eget. Vulputate dignissim suspendisse in 
est ante in nibh mauris. Magna fermentum iaculis eu non diam phasellus vestibulum lorem sed. Faucibus in ornare quam viverra orci sagittis eu volutpat. 
Ante metus dictum at tempor commodo ullamcorper a lacus vestibulum. Arcu dictum varius duis at consectetur lorem donec massa. Turpis egestas pretium aenean 
pharetra magna ac placerat. Turpis egestas pretium aenean pharetra magna ac placerat vestibulum. Faucibus scelerisque eleifend donec pretium. Vel turpis nunc 
eget lorem dolor sed viverra ipsum nunc. In fermentum et sollicitudin ac orci. Massa massa ultricies mi quis hendrerit dolor magna eget est. Sem integer vitae 
justo eget magna fermentum iaculis eu. Diam sollicitudin tempor id eu nisl nunc mi ipsum. Nunc consequat interdum varius sit amet mattis.
</pre>

Developing the About Us Component

  1. Run the following command in the command prompt:

ng generate component about-us

  1. In Visual Studio Code, open the file src > app > about-us > about-us.component.html, delete the contents of the file, and add following code:
1
2
3
4
5
6
7
8
9
10
11
<h1>About Us</h1>
<pre>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Aliquam sem fringilla ut morbi tincidunt. Feugiat nibh sed pulvinar proin gravida hendrerit. Sed blandit libero volutpat sed cras ornare. 
Est lorem ipsum dolor sit amet consectetur adipiscing. Bibendum at varius vel pharetra vel turpis nunc eget. Vulputate dignissim suspendisse in 
est ante in nibh mauris. Magna fermentum iaculis eu non diam phasellus vestibulum lorem sed. Faucibus in ornare quam viverra orci sagittis eu volutpat. 
Ante metus dictum at tempor commodo ullamcorper a lacus vestibulum. Arcu dictum varius duis at consectetur lorem donec massa. Turpis egestas pretium aenean 
pharetra magna ac placerat. Turpis egestas pretium aenean pharetra magna ac placerat vestibulum. Faucibus scelerisque eleifend donec pretium. Vel turpis nunc 
eget lorem dolor sed viverra ipsum nunc. In fermentum et sollicitudin ac orci. Massa massa ultricies mi quis hendrerit dolor magna eget est. Sem integer vitae 
justo eget magna fermentum iaculis eu. Diam sollicitudin tempor id eu nisl nunc mi ipsum. Nunc consequat interdum varius sit amet mattis.
</pre>

Developing the Navigation Bar

  1. Run the following command in the command prompt:

ng generate component nav-bar

  1. In Visual Studio Code, open the file src > app > nav-bar > nav-bar.component.html, delete the contents of the file, and add following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<nav class="navbar navbar-expand-sm bg-dark">
    <ul class="nav navbar-nav">
        <li class="nav-item">
            <a class="nav-link" href="#">Router Outlet Demo</a>
        </li>
        <li class="nav-item">
            <a [routerLink]="['/home']" class="nav-link" routerLinkActive="active"
                [routerLinkActiveOptions]="{exact:true}">Home</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" [routerLink]="['/about']" routerLinkActive="active">About</a>
        </li>
    </ul>
</nav>
  1. In Visual Studio Code, open the file src > app > nav-bar > nav-bar.component.css and add the following code:
1
li > a.active { color: #F97924 }

Setting up the Routes

  1. In Visual Studio Code, open the file src > app > app.module.ts.
  2. In the routes array, add the following entries:
1
2
{path:'home', component: HomeComponent},
{path:'about', component: AboutUsComponent}

Using the router-outlet Component

In Visual Studio Code, open the file src > app > app.component.html, delete the existing content, and add the following code. By doing so, you will be adding the router-outlet component to the mix so that different routes are rendered in it.

1
2
<app-nav-bar></app-nav-bar>
<router-outlet></router-outlet>

Testing the Application

You are now ready to use the router-outlet component.

  1. Run the following command in the command prompt to start Angular Development Server in watch mode: ng serve
  2. If prompted to share Angular CLI usage data, press the 'N' key to not share it.
  3. Open a browser and type the following URL in the address bar to launch the application: http://localhost:4200.
  4. Notice there are two links in the navigation bar titled Home and About.
  5. Click on the About link and notice the display below the navigation bar changes, showing the HTML of the About-us component.
  6. Click back on the Home link and notice the display below the navigation bar changes, showing the HTML of the Home component.

Conclusion

Congratulations! You have successfully used the router-outlet to render different application routes to the end-users. For more information, please visit Router Outlet in Angular.

4