How To Create Custom Module In Angular 8

In this tutorial, we will learn how to create a custom or feature module in Angular 8. Feature modules are NgModules for the purpose of organizing code. Custom or feature modules are used in Angular to group several components so as to organize the code for better readability and reusability.
Learn Angular 8 at Angular 8 Tutorials and Examples

Getting Started With Angular 8

I assume that you have installed Node.js. Now, we need to check the Node.js and NPM versions. Open the terminal or Node command line then type these commands.
C:\Angular>node -v
v10.15.3

C:\Angular>npm -v
6.9.0

Install the latest version of Angular CLI

To install or update Angular 8 CLI, type this command in the Terminal or Node Command-Line.
npm install -g @angular/cli
Now, let's check the latest version of Angular CLI:
C:\angular>ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 8.0.1
Node: 10.15.3
OS: win32 x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.800.1
@angular-devkit/core         8.0.1
@angular-devkit/schematics   8.0.1
@schematics/angular          8.0.1
@schematics/update           0.800.1
rxjs                         6.4.0

Create Angular 8 Application using Angular CLI

Let's use the below command to generate an Angular 8 application. We name this project as an "angular-custom-module".
ng new angular-custom-module

Create Module In Angular 8 App

Let's create an employee module using the following Angular CLI command:
C:\Angular\angular-custom-module>ng g module employee
CREATE src/app/employee/employee.module.ts (192 bytes)
It will create a folder inside the app directory called an employee, and inside the employee directory, you can see one file called employee.module.ts.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ]
})
export class EmployeeModule { }
Now we can create employee-related components, services under the employee module not directly under AppModule.

Create Angular Components

Now, let's create the following angular components related to an employee module.
PS C:\Angular\angular-custom-module\src\app> ng g c .\employee\employee-list
CREATE src/app/employee/employee-list/employee-list.component.html (28 bytes)
CREATE src/app/employee/employee-list/employee-list.component.spec.ts (671 bytes)
CREATE src/app/employee/employee-list/employee-list.component.ts (296 bytes)
CREATE src/app/employee/employee-list/employee-list.component.css (0 bytes)
UPDATE src/app/employee/employee.module.ts (380 bytes)

Create Model and Service for Employee

Let's create an Employee typescript class with the following command:
PS C:\Angular\angular-custom-module\src\app> ng g class .\employee\employee
CREATE src/app/employee/employee.spec.ts (162 bytes)
CREATE src/app/employee/employee.ts (26 bytes)
Let's create an EmployeeService class with the following Angular CLI command:
PS C:\Angular\angular-custom-module\src\app> ng g s .\employee\employee
CREATE src/app/employee/employee.service.spec.ts (343 bytes)
CREATE src/app/employee/employee.service.ts (137 bytes)

Integrate Bootstrap with Angular

Use NPM to download Bootstrap & JQuery. Bootstrap and jQuery will be installed into the node_modules folder.
npm install bootstrap jquery --save
Configure installed Bootstrap & JQuery in an angular.json file:
...
 
"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
  "node_modules/jquery/dist/jquery.min.js",
  "node_modules/bootstrap/dist/js/bootstrap.min.js"
]
 
...
If bootstrap.min.css won't work then import this bootstrap.min.css in a style.css file like this:
/* You can add global styles to this file, and also import other style files */
@import url(https://unpkg.com/[email protected]/dist/css/bootstrap.min.css)

employee.ts - Employee Model

We have created employee.ts file using Angular CLI, now add following code to it:
export class Employee {
    id: number;
    firstName: string;
    lastName: string;
    emailId: string;
}

employee.service.ts - EmployeeService

We have created employee.service.ts file using Angular CLI, now add following code to it:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Employee } from './employee';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor() { }

  employees : Employee[] = [{
    "id": 1,
    "firstName": "ramesh",
    "lastName": "Fadatare",
    "emailId": "[email protected]"
  },

  {
    "id": 2,
    "firstName": "Tony",
    "lastName": "Stark",
    "emailId": "[email protected]"
  }]

  public getEmployees(): any {
    const employeesObservable = new Observable(observer => {
      setTimeout(() => {
        observer.next(this.employees);
      }, 1000);
    });

    return employeesObservable;
  }
}

employee-list.component.ts - EmployeeListComponent

We have created an employee-list.component.ts file using Angular CLI, now add following code to it:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Employee } from '../employee';
import { EmployeeService } from '../employee.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {

  employees: Observable<Employee[]>;

  constructor(private employeeService: EmployeeService) {}

  ngOnInit() {
    this.getEmployees();
  }

  getEmployees() {
    this.employees = this.employeeService.getEmployees();
  }
}

employee-list.component.html - HTML Component Template

<div class="panel panel-primary">
    <div class="panel-heading">
      <h2>Employee List</h2>
    </div>
    <div class="panel-body">
      <table class="table table-striped">
        <thead>
          <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let employee of employees | async">
            <td>{{employee.firstName}}</td>
            <td>{{employee.lastName}}</td>
            <td>{{employee.emailId}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

Importing a Feature or Custom Module

To incorporate the feature module into our app, we have to let the root module, app.module.ts, know about it. Notice the EmployeeModule export at the bottom of employee.module.ts. This exposes it so that other modules can get to it. 
To import it into the AppModule, add it to the imports in app.module.ts and to the imports array:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
// import the feature module here so you can add it to the imports array below
import { EmployeeModule } from './employee/employee.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    EmployeeModule    // add the feature module here
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Configure the Routing - AppRoutingModule

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EmployeeListComponent } from './employee/employee-list/employee-list.component';

const routes: Routes = [
  {
      path: '',
      component: EmployeeListComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.ts - AppComponent

The app.component.ts file defines the logic for the app's root component, named AppComponent. The view associated with this root component becomes the root of the view hierarchy as you add components and services to your application.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-custom-module';
}

app.component.html

The app.component.html file defines the HTML template associated with the root AppComponent.
<div class="container">
     <router-outlet></router-outlet>
</div>

Running Angular 8 Application

Let's run the above developed Angular App with a command:
ng serve
By default, the Angular app runs on 4200 port. Hit http://localhost:4200/ link in the browser will open the below page on the screen.
Learn Angular 8 at Angular 8 Tutorials and Examples

Comments