Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Displaying Routed Content with routerOutlet in Angular

Jun 26, 2020 • 9 Minute Read

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 
  2. When prompted to add routing to the application, press 'N'.
  3. 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 
  2. Run the following command to install jquery:  npm i jquery 
  3. Run the following command to install Bootstrap:  npm i bootstrap 
  4. In Visual Studio Code, open the file angular.json.
  5. Add the following line in the styles array before src/style.css.  "node_modules/bootstrap/dist/css/bootstrap.min.css", 
  6. Add the following lines in the scripts array:  "node_modules/jquery/dist/jquery.min.js", "node_modules/bootstrap/dist/js/bootstrap.min.js" 
  7. In Visual Studio Code, open the file src > index.html.
  8. At line number 10 of the body element, add the following class:  class="container"  The final code should look like this: 
      <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. 

      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 
  2. In Visual Studio Code, open the file src > app > home > home.component.html, delete the existing content, and add following code: 
      <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 
  2. 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: 
      <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 
  2. 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: 
      <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>
    

 3. In Visual Studio Code, open the file src > app > nav-bar > nav-bar.component.css and add the following code: 

      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: 
      {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. 

      <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: https://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.

Parul Saxena

Parul S.

Parul Saxena is a professional developer, instructor, technical writer and ex-IBM consultant. Her career spans more than 14 years. She has designed and delivered enterprise-grade middleware solutions using IBM Enterprise Service Bus, DataPower and WebSphere to high profile retail and banking enterprises across the world. She has designed and implemented DevOps processes using AWS DevOps for consulting engagements in IBM Global Services. In addition, she has also written support workbooks and designed e-learning courses for multiple SaaS products.

More about this author