Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

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

May 11, 2020 • 8 Minute Read

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.

      $ ng new imports-array-demo
    

Create a feature module.

      $ ng g m pagination
    

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

      $ ng g c pagination/components/pager
    

The project is set up.

Now, make changes in pager.component.ts.

pager.component.ts

      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);
  }
}
    

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

      <div style="text-align: center">
  <button *ngFor="let number of numbers" (click)="onNumberClick(number)">
    {{number}}
  </button>
</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

      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 {}
    

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

      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 {}
    

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

      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);
  }
}
    

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

      <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>
    

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.

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.