AppDividend
Latest Code Tutorials

How To Create Angular Modules To Organize Code

0

In this tutorial, we will see How To Create Angular Modules To Organize Code. Modules are the great way to organize an application and extend it with capabilities from external libraries. Angular libraries are NgModules, such as FormsModuleHttpClientModule, and RouterModule. There are many third-party libraries are available as NgModules such as Material DesignIonic, and AngularFire2. Angular Modules can also add services to the application. Such services might be internally developed, like something you would prepare your application.

If you want to learn more about Angular, then check out this Angular 7 – The complete Guide course.

Feature Modules

Feature modules are NgModules to organize code. As your app scales, you can organize code relevant for a specific feature. Feature Modules helps us to apply the clear boundaries for your features. With Feature Modules, you can keep code related to the particular functionality or feature separate from other code.

Difference b/w Feature Modules and Root Modules

The feature module is an organizational best practice, as opposed to the concept of the core Angular API. The feature module delivers a cohesive set of functionality focused on a specific application need such as the user workflow, routing, or forms. While you can do everything within the root module, feature modules help you partition the app into focused areas.

How To Create Angular Modules

Let us install brand new Angular 7 project and then we use Feature Modules to organize our project.

Step 1: Install Angular 7

Let us create a new Angular Project.

ng new angmodules

 

How To Create Angular Modules To Organize Code

We will use Angular Routing, but not provided by Angular CLI because it is not needed. We will be creating only one route for this demo.  Now, go inside the folder and open the project on your editor. I am using VSCode.

cd angmodules && code .

Also, add the Bootstrap using the following command.

npm install bootstrap --save

Now, add the bootstrap file inside the angular.json file.

"styles": [
   "src/styles.css",
   "./node_modules/bootstrap/dist/css/bootstrap.min.css"
],

Now, we can use Bootstrap in our application.

Step 2: Create a new Angular Module

Assuming you already have an app that you created with the Angular CLI, create the feature module using an Angular CLI by entering the following command in the root project directory.

ng g module student

It will create a folder inside the app directory called a student, and inside the student directory, you can see one file called student.module.ts.

// student.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ]
})
export class StudentModule { }

So that means if we have any functionalities or components related to the student, it will be imported here in this student.module.ts file and not directly inside the app.module.ts file as we generally used to do.

Next step is to create the three angular components related to student module. So let us do that.

Step 3: Create Angular Components

Now, we will create the following three angular components related to a student module.

  1. student.component.ts
  2. student-list.component.ts
  3. student-list-item.component.ts
Related Posts
1 of 22

So type the following command to generated above angular components.

ng g c student/student --spec=false
ng g c student/student-list --spec=false
ng g c student/student-list-item --spec=false

You can see that all of the components are created inside the app >> student folder and now you can see the student.module.ts file. All of the three components are automatically imported inside the student.module.ts file.

// student.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { StudentListComponent } from './student-list/student-list.component';
import { StudentListItemComponent } from './student-list-item/student-list-item.component';
import { StudentComponent } from './student/student.component';

@NgModule({
  declarations: [StudentComponent, StudentListComponent, StudentListItemComponent],
  imports: [
    CommonModule
  ]
})
export class StudentModule { }

Import the student.module.ts file inside the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { StudentModule } from './student/student.module';

import { AppComponent } from './app.component';

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

So, now we have registered the new module to the angular application. Now, start the angular development server to see if we do not get any errors.

ng serve

 

Angular 7 Modules Example Tutorial

Step 4: Create a model and service for student

You can create a service using the following command.

ng g s student/student --spec=false

It will create a file like this.

// student.service.ts

import { Injectable } from '@angular/core';

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

  constructor() { }
}

Now, inside the student folder, create one file called student.model.ts and add the following code.

// student.model.ts

export class Student {
    id: Number;
    name: String;
    enrollno: Number;
    college: String;
    university: String;
}

So, this is our model class Student. We are displaying this kind of data to the frontend.

Now, write the following code inside the student.service.ts file.

// student.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

import { Student } from './student.model';

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

    students: Student[] = [{
        id: 1,
        name: 'Krunal',
        enrollmentnumber: 110470116021,
        college: 'VVP Engineering College',
        university: 'GTU'
    },
    {
        id: 2,
        name: 'Rushabh',
        enrollmentnumber: 110470116023,
        college: 'VVP Engineering College',
        university: 'GTU'
    },
    {
        id: 3,
        name: 'Ankit',
        enrollmentnumber: 110470116022,
        college: 'VVP Engineering College',
        university: 'GTU'
    }];

    constructor() { }

    public getStudents(): any {
        const studentsObservable = new Observable(observer => {
            setTimeout(() => {
                observer.next(this.students);
            }, 1000);
        });

        return studentsObservable;
    }
}

So, in this file, we have defined the getStudents function that will return the Observables. So when the subscriber wants the data from the publisher, it will subscribe to this studentsObservable and publisher start publishing the values, and eventually, subscriber get the data. If you are unfamiliar with Observables, then please check out my this Angular Observables Tutorial With Example article.

Now, the final step is to prepare all the components to display the data coming from student service.

Step 5: Configure the routing.

Add the following code inside the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { StudentModule } from './student/student.module';

import { AppComponent } from './app.component';
import { StudentComponent } from './student/student/student.component';

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    StudentModule,
    RouterModule.forRoot(routes),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here, I have imported the Routes and RouterModule and then create an array of route and register to our angular application.

Now, we need to display the component by using router-outlet inside the app.component.html file.

<div class="container">
    <router-outlet></router-outlet>
</div>

So till now what we have done is if the user goes to the http://localhost:4200, we will display the student.component.html view. So our next step is to add the HTML code that view.

Step 6: Display the data

The first thing is to write the following code inside the student.component.html file.

<div>
    <app-student-list></app-student-list>
</div>

So this is our outer most component, and inside this component, there is student-list.component.html component.

Now, write the following code inside the student-list.component.ts file.

// student-list.component.ts

import { Component, OnInit } from '@angular/core';
import { StudentService } from '../student.service';
import { Student } from '../student.model';

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

    students: Student[] = [];

    constructor(private studentservice: StudentService) { }

    ngOnInit() {
        const studentObservable = this.studentservice.getStudents();
        studentObservable.subscribe((studentsData: Rental[]) => {
            this.students = studentsData;
        });
    }
}

Also, write the following HTML inside the student-list.component.html file.

<div class="row">
    <div class="col-md-3 col-xs-6" *ngFor="let student of students">
        <app-student-list-item [student]="student"></app-student-list-item>
    </div>
</div>

So, we are passing the data from parent to the child component. So, app-student-list-component will expect the one input value called student.

Now, write the following code inside the student-list-item.component.ts file.

// student-list-item.component.ts

import { Component, OnInit, Input } from '@angular/core';

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

    @Input() student: any;

    constructor() { }

    ngOnInit() {
    }

}

Add the HTML code inside the student-list-item.component.html file.

<div class="card">
    <div class="card-body">
        <h5 class="card-title">{{ student.name }}</h5>
        <h6 class="card-subtitle">{{ student.enrollmentno }}</h6>
        <p class="card-text">{{ student.college }}</p>
        <p class="card-text">{{ student.university }}</p>
        <a class="btn btn-primary" href="#" >Go somewhere</a>
    </div>
</div>

Save the file and go to the http://localhost:4200/ and you will see something like this after 1 second.

 

Angular Modules Example

Conclusion

So, here we have taken our whole project module-wise for the student by creating a file called student.module.ts.

All the functionality and code related the student will reside on app >> student folder and you can create as many modules as you want by separating them to each of that respected folder.

Feature Modules is the best way to organize your scalable code; you do not need to register all of your components inside the app.module.ts file, you will create one module file respected to your functionality and add your components inside them.

Finally, you can add the module inside the app.module.ts file, and you are good to go. This is one of the best ways to organize your project.

At last How To Create Angular Modules To Organize Code Tutorial With Example is over.

 

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.