Create a simple CRUD app

Angular 15

Create an application with ngModules and nested routes

In this step-by-step tutorial you will learn how to create a multiview application using Angular 15, with custom ngModules (core, feature and shared), lazy loading, primary and nested routes

2022-02-25
8 min read
Difficulty
angular
typescript

Goal

In this tutorial you learn:

  • How to use angular-cli generators for modules and components
  • How to create a multiview Angular Single Page Application (SPA) organized in custom ngModules (core, features and shared)
  • How to use lazy loading with root and children routes

Following you can see the result you'll get at the end of the tutorial:

lazy loading

The core of the application is loaded by an unique bundle (main.js) but each view is loaded "on-demand" with its own chunk ( a separated JavaScript file), that is loaded the first time a route is requested:

As a result, these views will be loaded when user explicitly requests them:

  • app-features-home-home-module.js
  • app-features-settings-settings-module.js
  • app-features-users-users-module.js

In the next recipes you will also be able to lazy load children routes (I mean a primary route with a secondary navigation bar with children routes).

TOPICS

Requirements

First time using Angular?

Probably you should start from my Angular Hello World Tutorial

The only requirement you need to make this exercise is NodeJS version 16 or above:

TIPS: multiple Node versions

If you need to install multiple versions of Node on your machine you might want to consider tools like nvm (node version manager). You could then have an Angular 10 project running on Node 12 and one with React that requires Node 18 at the same time.

Links: NVM Windows | Install on Mac using HomeBrew

Create an Angular project with Angular CLI

Open the terminal, go to the folder in which you would like to create a new Angular project and type the following command to quickly generate an Angular project with the latest version of the framework:

npx -p @angular/cli@latest ng new angular15-router-and-ngmodules  -s -t -S

or, you can install the exact same version I have used to build this tutorial

npx -p @angular/cli@15.2.0 ng new angular15-router-and-ngmodules  -s -t -S

When asked:

  • Ok to proceed?: Type y
  • Would you like to add Angular routing?: Yes
  • Which stylesheet format would you like to use: Use arrows and select CSS

What is NPX?

The npx (Node Package eXecute) is an NPM package runner and it's automatically installed with Node and NPM.

It allows developers to execute any Javascript Package available on the NPM registry without even installing it. So we use this command to download the latest Angular version, install all the dependencies and create a new project named demo1

npx -p @angular/cli@latest ng new [PROJECT_NAME]  -s -t -S

Other parameters:

  • -t: enable inline templates instead of create external HTML files for components
  • -s: enable inline styles
  • -S: skip (unit) tests

Why do we set these parameters?


In Angular you can define the HTML and CSS in external files or, if you prefer, you can integrate them directly into the component. I prefer the latter solution because, in this way, we avoid too many files inside the application. It's a personal choice that not everyone likes so I suggest you use it to complete this tutorial and you can always switch to external templates in future projects.

Now you can open the terminal and run the project you have just created:

cd angular15-router-and-ngmodules            # go to project folder
npm start                                    # run project ... wait some seconds

Check if it works

After the project compilation, you can navigate to http://localhost:4200 and open the project in your favorite browser to get a preview. I suggest to use Chrome (or Firefox).

TIPS

  1. You can check the terminal for compilation errors (anyway they are also often shown in the browser)
  2. you should always keep opened browser DevTools to check if there are runtime errors, as shown in the image below

Project Structure

Your project structure should look like to the following:

Install Bootstrap

Open your terminal and kill the current process by pressing CTRL + C (probably you need to press it a couple of times).

Now you can install Bootstrap, a CSS framework useful to quickly create HTML layouts, by using its npm package.

Make sure you're in the project root folder and run the following command:

npm install bootstrap

How can I be sure I'm the root folder?

You're in the root file if it contains the package.json file.
Use dir command (Windows) or ls (Mac/Linux) to display the list of files:

Global CSS

Bootstrap CSS classes should be globally available in our application since we're using it in several components.

The easiest way to include it in our project is by opening the angular.json file and update the architect.build.styles property.

So, open angular.json (you can find it in the project root folder) and recognize the styles property:

angular.json
// ...
"architect": {
  "build": {
    // ...
    "options": {
      // ...
      "styles": [     // <=== HERE
        "src/styles.css"
      ],
    }
  }
// ...
}

And now you can add the path of the minified CSS version of the framework you have just installed:

angular.json
{
  // ...
  "styles": [
    "node_modules/bootstrap/dist/css/bootstrap.min.css",
    "src/styles.css"
  ],
  // ...
}

How did I find the Bootstrap path to include in `angular.json`

You just need to open your node_modules folder, search the bootstrap folder and find the file path:

Check if Bootstrap works

Now you just need to check if Bootstrap is properly configured.

You have to kill the Angular CLI process by pressing CTRL + C and run npm start again to apply the changes you have done in angular.json (since this file is evaluated only the first time, when the applications starts)

Open src/app.component.ts and replace all the HTML template content with the following one:

Angular
app.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
template: `
  <button class="btn btn-success">
    Bootstrap Button
  </button>

  <router-outlet></router-outlet>
`,
})
export class AppComponent {}

What is 'router-outlet'?

router-outlet is a component provided by Angular Router to dinamically loads your pages / modules.

In fact, as we'll see in the next recipes, you can specify to load a component or a module when a specific path is visited, and it will be automatically loaded inside the router-outlet that handle like a placeholder to decide the position where you want to load it

Now you can save your work, wait a moment and you should see the following output in your browser (a green button):

You can now remove the <button> you have just created. It was just a test to check if Bootstrap is properly installed and configured 😅

Angular
app.component.ts
  import { Component } from '@angular/core';

  @Component({
    selector: 'app-root',
    template: `
      <router-outlet></router-outlet>
    `,
  })
  export class AppComponent {}

VISUAL STUDIO CODE TIPS

Some IDE such as WebStorm supports Angular inline template out of the box.

Visual Studio Code (VSC) doesn't support them.

So I suggest to install the angular2-inline extension from the VSC marketplace

Anyway I also suggest to install the Angular Service extension or, much better, Angular Essential by John Papa (a pack of extensions thats already includes it and several other useful extensions for Angular)


ADS: MY LATEST VIDEO COURSE <br />(italian only)ADS: MY LATEST VIDEO COURSE <br />(italian only)
ADS: MY LATEST VIDEO COURSE
(italian only)

Keep updated about latest content
videos, articles, tips and news