Author avatar

Gaurav Singhal

How to Pull in External Exported Features Using the Imports Array in Angular

Gaurav Singhal

  • May 11, 2020
  • 8 Min read
  • 244 Views
  • May 11, 2020
  • 8 Min read
  • 244 Views
Languages Frameworks and Tools
Front End Web Developer
Client-side Frameworks
Angular

Introduction

In this guide, you will learn how to import feature modules into a project so you can keep functionalities separate from each other and use them according to your needs. A module is a combination of pipes, directives, and components. You can import a module to help you make an application. It's always good to divide your application into different parts and organize your code according to your timeline to help you get relevant information about each module quickly. Feature modules help you to minimize errors and improve your productivity.

Predefined Feature Modules In Angular

Angular comes with some default feature modules to help you focus on functionality instead of implementing it from scratch. These modules fulfill your basic requirements. They include:

  1. CommonModule : Exports basic directives such as NgIf, NgForOf etc.

  2. FormsModule: Exports providers and directive for template-driven forms such as MinLengthValidator or MaxLengthValidator.

Create Your Own Feature Module

In this section, you'll make a custom feature module. In this feature module, you'll implement pagination functionality. As mentioned, a feature module can export components, directives, and pipes. In this feature, you will export a component.

You'll display a listof values with the help of pagination so users don't have to scroll too much and can get the next items by clicking on the page number.

Start by creating a project. Take a look at the following code snippet.

1
$ ng new imports-array-demo
console

Create a feature module.

1
$ ng g m pagination
console

Create a component within a feature module so you can export it.

1
$ ng g c pagination/components/pager
console

The project is set up.

Now, make changes in pager.component.ts.

pager.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core";
import { Subject } from "rxjs";

@Component({
  selector: "app-pager",
  templateUrl: "./pager.component.html",
  styleUrls: ["./pager.component.scss"]
})
export class PagerComponent implements OnInit {
  @Input() pageSize: number;
  @Input() totalRecords: number;
  @Output() pageNumber = new EventEmitter<any>();
  firstPageNumber: number;
  lastPageNumber: number;
  currentPageNumber: number;
  numbers: number[];
  constructor() {
    this.firstPageNumber = 1;
    this.currentPageNumber = 1;
    this.numbers = [];
  }

  ngOnInit() {}

  ngOnChanges() {
    this.onGenerateNumbers();
  }

  onGenerateNumbers() {
    this.lastPageNumber = Math.ceil(this.totalRecords / this.pageSize);
    for (let i = 1; i <= this.lastPageNumber; i++) {
      this.numbers.push(i);
    }
  }

  onNumberClick(number) {
    this.pageNumber.emit(number);
  }
}
ts

Here you are accepting pageSize and totalRecords from the parent component. These two requirements help generate page numbers. In the onGenerateNumbers() function, the generated numbers are stored in the array.

Next, emit an event when a user clicks on the numbers.

In the HTML template, display the numbers that you have created in a onGenerateNumbers() function.

pager.component.html

1
2
3
4
5
<div style="text-align: center">
  <button *ngFor="let number of numbers" (click)="onNumberClick(number)">
    {{number}}
  </button>
</div>
html

Every button of a number is bound with a click function that will call the onNumberClick() function. This function will emit the number that was clicked by the user.

To use this component in AppComponent, export it from a feature module.

pagination.module.ts

1
2
3
4
5
6
7
8
9
10
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { PagerComponent } from "./components/pager/pager.component";

@NgModule({
  declarations: [PagerComponent],
  imports: [CommonModule],
  exports: [PagerComponent]
})
export class PaginationModule {}
ts

Now you can import it into any other module where you want to use the pager component.

For now, import it in AppModule.

app.module.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";

import { AppComponent } from "./app.component";
import { HttpClientModule } from "@angular/common/http";
import { PaginationModule } from "./pagination/pagination.module";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, PaginationModule, HttpClientModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
ts

Here you can see that in the imports array of the module, you have imported the feature module PaginationModule.

Now you're going to use the component of pagination. You need to get the data in the first place to fulfill the requirements of the pager component.

app.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent {
  posts: any;
  currentPagenumber: number;
  pageSize: number;
  totalRecords: number;
  paginatedPosts: any;

  constructor(private _httpClient: HttpClient) {}

  ngOnInit() {
    this.currentPagenumber = 1;
    this.pageSize = 12;
    this.getData();
  }

  getData() {
    let URL = "https://jsonplaceholder.typicode.com/posts";
    this._httpClient.get(URL).subscribe(posts => {
      this.posts = posts;
      this.totalRecords = this.posts.length;
      this.paginatedPosts = this.pagination(
        this.posts,
        this.currentPagenumber,
        this.pageSize
      );
    });
  }

  onGetPageNumber(number) {
    this.currentPagenumber = number;
    this.paginatedPosts = this.pagination(
      this.posts,
      this.currentPagenumber,
      this.pageSize
    );
  }

  pagination(items, pageNumber, pageSize) {
    let startIndex = (pageNumber - 1) * pageSize;
    let endIndex = startIndex + pageSize;
    return items.slice(startIndex, endIndex);
  }
}
ts

In AppComponent, create an ajax request and get the data of posts. Store the length of the posts in totalRecords. You need a page size that decides the items in a page. In the constructor, set the page size as 12.

The onGetPageNumber() function accepts the page number that is hitting from the pager component. It will play a role as a currentPageNumber.

You have written a small function, pagination(), that will return the items from the posts array as per currentPageNumber.

Next, write a pager component in app.component.html.

app.component.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div style=" display: flex; flex-wrap: wrap;justify-content: center">
  <div
    *ngFor="let post of paginatedPosts"
    style="width: calc(90% / 3);box-sizing: border-box;padding: 10px;box-shadow: 0 0 2px 0px; margin: 10px;"
  >
    <div>
      <span><b>Id:</b>{{post.id}}</span>
      <p><b>Title:</b>{{post.title}}</p>
      <p><b>Body:</b>{{post.title}}</p>
    </div>
  </div>
</div>
<app-pager
  [pageSize]="pageSize"
  [totalRecords]="totalRecords"
  (pageNumber)="onGetPageNumber($event)"
></app-pager>
html

Now, run the project and check out the results.

imagur.

In the output, you can see that your data has been successfully rendered in the browser, and the pager component is working correctly.

Kudos! You have successfully made a feature module and exported a component that is then imported into AppModule using the imports array.

Conclusion

In this guide, we learned about feature modules and how to import them using the imports array. Angular has many predefined feature modules that will help you solve problems and complete your application in less time. You can read more about this here. You can also explore the pager component, and as you add more features, it will become your own new library.

3