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.
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:
CommonModule : Exports basic directives such as NgIf, NgForOf etc.
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
Create a feature module.
1$ ng g m pagination
Create a component within a feature module so you can export it.
1$ ng g c pagination/components/pager
The project is set up.
Now, make changes in pager.component.ts.
pager.component.ts
1import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core";
2import { Subject } from "rxjs";
3
4@Component({
5 selector: "app-pager",
6 templateUrl: "./pager.component.html",
7 styleUrls: ["./pager.component.scss"]
8})
9export class PagerComponent implements OnInit {
10 @Input() pageSize: number;
11 @Input() totalRecords: number;
12 @Output() pageNumber = new EventEmitter<any>();
13 firstPageNumber: number;
14 lastPageNumber: number;
15 currentPageNumber: number;
16 numbers: number[];
17 constructor() {
18 this.firstPageNumber = 1;
19 this.currentPageNumber = 1;
20 this.numbers = [];
21 }
22
23 ngOnInit() {}
24
25 ngOnChanges() {
26 this.onGenerateNumbers();
27 }
28
29 onGenerateNumbers() {
30 this.lastPageNumber = Math.ceil(this.totalRecords / this.pageSize);
31 for (let i = 1; i <= this.lastPageNumber; i++) {
32 this.numbers.push(i);
33 }
34 }
35
36 onNumberClick(number) {
37 this.pageNumber.emit(number);
38 }
39}
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<div style="text-align: center">
2 <button *ngFor="let number of numbers" (click)="onNumberClick(number)">
3 {{number}}
4 </button>
5</div>
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
1import { NgModule } from "@angular/core";
2import { CommonModule } from "@angular/common";
3import { PagerComponent } from "./components/pager/pager.component";
4
5@NgModule({
6 declarations: [PagerComponent],
7 imports: [CommonModule],
8 exports: [PagerComponent]
9})
10export class PaginationModule {}
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
1import { BrowserModule } from "@angular/platform-browser";
2import { NgModule } from "@angular/core";
3
4import { AppComponent } from "./app.component";
5import { HttpClientModule } from "@angular/common/http";
6import { PaginationModule } from "./pagination/pagination.module";
7
8@NgModule({
9 declarations: [AppComponent],
10 imports: [BrowserModule, PaginationModule, HttpClientModule],
11 providers: [],
12 bootstrap: [AppComponent]
13})
14export class AppModule {}
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
1import { Component } from "@angular/core";
2import { HttpClient } from "@angular/common/http";
3
4@Component({
5 selector: "app-root",
6 templateUrl: "./app.component.html",
7 styleUrls: ["./app.component.scss"]
8})
9export class AppComponent {
10 posts: any;
11 currentPagenumber: number;
12 pageSize: number;
13 totalRecords: number;
14 paginatedPosts: any;
15
16 constructor(private _httpClient: HttpClient) {}
17
18 ngOnInit() {
19 this.currentPagenumber = 1;
20 this.pageSize = 12;
21 this.getData();
22 }
23
24 getData() {
25 let URL = "https://jsonplaceholder.typicode.com/posts";
26 this._httpClient.get(URL).subscribe(posts => {
27 this.posts = posts;
28 this.totalRecords = this.posts.length;
29 this.paginatedPosts = this.pagination(
30 this.posts,
31 this.currentPagenumber,
32 this.pageSize
33 );
34 });
35 }
36
37 onGetPageNumber(number) {
38 this.currentPagenumber = number;
39 this.paginatedPosts = this.pagination(
40 this.posts,
41 this.currentPagenumber,
42 this.pageSize
43 );
44 }
45
46 pagination(items, pageNumber, pageSize) {
47 let startIndex = (pageNumber - 1) * pageSize;
48 let endIndex = startIndex + pageSize;
49 return items.slice(startIndex, endIndex);
50 }
51}
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<div style=" display: flex; flex-wrap: wrap;justify-content: center">
2 <div
3 *ngFor="let post of paginatedPosts"
4 style="width: calc(90% / 3);box-sizing: border-box;padding: 10px;box-shadow: 0 0 2px 0px; margin: 10px;"
5 >
6 <div>
7 <span><b>Id:</b>{{post.id}}</span>
8 <p><b>Title:</b>{{post.title}}</p>
9 <p><b>Body:</b>{{post.title}}</p>
10 </div>
11 </div>
12</div>
13<app-pager
14 [pageSize]="pageSize"
15 [totalRecords]="totalRecords"
16 (pageNumber)="onGetPageNumber($event)"
17></app-pager>
Now, run the project and check out the results.
.
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.
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.