Published: April 29 2019

Angular 7 Tutorial Part 3 - Add Routing & Multiple Pages

Other parts available in Angular 7 tutorial series:


Angular 7 Tutorial Part 3

In part 3 of this Angular 7 tutorial series we're going to add multiple pages to our app and enable navigation between them with routing.

The complete source code for this part of the tutorial is available on github at https://github.com/cornflourblue/angular-7-tutorial in the part-3 folder. If you haven't completed Part 2 (Create Base Project Structure & Webpack Config) but want to follow the steps in this part of the tutorial series you can start with the code in the part-2 folder of the github repo.

Steps:

  1. Create Page Components
  2. Add Components to App Module
  3. Configure App Routing
  4. Add App Routing Module to App Module
  5. Add Router Outlet and Navigation to App Component
  6. Update Webpack Dev Server Config
  7. Start Angular 7 Application!


Create Page Components

The Angular 7 app will contain three pages - Home, Login and Register. For now each of the page components will just display a title so we can test navigating between them.

An Angular component is a class that contains the logic to control a piece of the UI. A class becomes an Angular component when it is decorated with the @Component decorator. For more info on Angular components see https://angular.io/guide/architecture-components.

Home Page Component & Template

Create a home folder inside the app folder and create a file named home.component.html inside the home folder, this is the home component template. Add the following HTML code to the home component template:

<h1>Home Page</h1>


Create a file named home.component.ts inside the home folder, this is the home component. Add the following TypeScript code to the home component:

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

@Component({ templateUrl: 'home.component.html' })
export class HomeComponent {}


Create a file named index.ts inside the home folder, this is a barrel file that re-exports components from the home folder so they can be imported in other files using only the folder path (e.g. './home') instead of the full path to the component (e.g. './home/home.component'). For more info on TypeScript barrel files see https://basarat.gitbooks.io/typescript/docs/tips/barrel.html.

Add the following TypeScript code to the barrel file:

export * from './home.component';


Login Page Component & Template

Create a login folder inside the app folder and create a file named login.component.html inside the login folder, this is the login component template. Add the following HTML code to the login component template:

<h1>Login Page</h1>


Create a file named login.component.ts inside the login folder, this is the login component. Add the following TypeScript code to the login component:

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

@Component({ templateUrl: 'login.component.html' })
export class LoginComponent {}


Create a file named index.ts inside the login folder, this is a TypeScript barrel file. Add the following TypeScript code to the barrel file:

export * from './login.component';


Register Page Component & Template

Create a register folder inside the app folder and create a file named register.component.html inside the register folder, this is the register component template. Add the following HTML code to the register component template:

<h1>Register Page</h1>


Create a file named register.component.ts inside the register folder, this is the register component. Add the following TypeScript code to the register component:

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

@Component({ templateUrl: 'register.component.html' })
export class RegisterComponent {}


Create a file named index.ts inside the register folder, this is a TypeScript barrel file. Add the following TypeScript code to the barrel file:

export * from './register.component';


Add Components to App Module

Open the App Module (/src/app/app.module.ts) in VS Code and add the page components to the declarations array, this will make the page components available to the other components in the App Module.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { HomeComponent } from './home';
import { LoginComponent } from './login';
import { RegisterComponent } from './register';

@NgModule({
    imports: [BrowserModule],
    declarations: [
        AppComponent,
        HomeComponent,
        LoginComponent,
        RegisterComponent
    ],
    bootstrap: [AppComponent]
})
export class AppModule { };


Configure App Routing Module

Create a file named app.routing.ts inside the app folder, this is the app routing module.

Routing for the Angular app is configured as an array of Routes, each component is mapped to a path so the Angular Router knows which component to display based on the URL in the browser address bar.

The Routes array is passed to the RouterModule.forRoot() method which creates a routing module with all of the app routes configured, and also includes all of the Angular Router providers and directives such as the <router-outlet></router-outlet> directive that we'll be using shortly. For more information on Angular Routing and Navigation see https://angular.io/guide/router.

Add the following TypeScript to the app routing module:

import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './home';
import { LoginComponent } from './login';
import { RegisterComponent } from './register';

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'login', component: LoginComponent },
    { path: 'register', component: RegisterComponent },

    // otherwise redirect to home
    { path: '**', redirectTo: '' }
];

export const appRoutingModule = RouterModule.forRoot(routes);


Add App Routing Module to App Module

Open the App Module (/src/app/app.module.ts) in VS Code and add the app routing module (appRoutingModule) to the imports array, this will make the Angular Router providers and directives available to the other components in the App Module.

The updated app.module.ts should look like this:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { appRoutingModule } from './app.routing';
import { AppComponent } from './app.component';
import { HomeComponent } from './home';
import { LoginComponent } from './login';
import { RegisterComponent } from './register';

@NgModule({
    imports: [
        BrowserModule,
        appRoutingModule
    ],
    declarations: [
        AppComponent,
        HomeComponent,
        LoginComponent,
        RegisterComponent
    ],
    bootstrap: [AppComponent]
})
export class AppModule { };


Add Router Outlet and Navigation to App Component

Open the app component template (/src/app/app.component.html) in VS Code and replace the <h1>Hello Angular 7!</h1> message with the below HTML code.

The app component template includes a main navigation that will be displayed at the top of the page, and a main content area that will display the page component that is mapped to the current path in the browser address bar.

The routerLink Angular directive enables navigation between different routes, and the <router-outlet></router-outlet> Angular directive displays the component for the current route. For more information on Angular Routing and Navigation see https://angular.io/guide/router.

This is how the updated app component template should look:

<!-- nav -->
<nav class="navbar navbar-expand navbar-dark bg-dark">
    <div class="navbar-nav">
        <a class="nav-item nav-link" routerLink="/">Home</a>
        <a class="nav-item nav-link" routerLink="/login">Login</a>
        <a class="nav-item nav-link" routerLink="/register">Register</a>
    </div>
</nav>

<!-- main content container -->
<div class="jumbotron">
    <div class="container">
        <div class="row">
            <div class="col-sm-8 offset-sm-2">
                <router-outlet></router-outlet>
            </div>
        </div>
    </div>
</div>


Update Webpack Dev Server Config

Add the following code to webpack.config.js to prevent 404 errors when the browser is refreshed. It tells the webpack dev server to always serve /index.html regardless of the URL path so Angular can initialise and handle routing instead of trying to handle it on the server.

devServer: {
    historyApiFallback: true
}


The updated webpack.config.js should look like this:

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/main.ts',
    resolve: {
        extensions: ['.ts', '.js']
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: ['ts-loader', 'angular2-template-loader']
            },
            {
                test: /\.(html|css)$/,
                use: 'raw-loader'
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({ template: './src/index.html' })
    ],
    devServer: {
        historyApiFallback: true
    }
}


Start Angular 7 Application!

Run the command npm start from the project root folder (where the package.json is located) to launch the Angular 7 application.


Need Some Angular 7 Help?

Search fiverr for freelance Angular 7 developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by