In this tutorial, we will see how to create Angular Modules to organize code. Feature modules are NgModules to organize code. As your app scales, you can organize code relevant to a specific feature. In addition, feature Modules help us apply 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 instead of 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.
Angular Modules
Modules in Angular are a great way to organize an application and extend it with capabilities from external libraries. Angular libraries are NgModules, such as FormsModule, HttpClientModule, and RouterModule. Many third-party libraries are available as NgModules, such as Material Design, Ionic, and AngularFire2. Angular Modules can also add services to the application. Such services might be internally developed, like something you prepare for your application.
Let us install a brand new Angular project, and then we use Feature Modules to organize our project.
Step 1: Install Angular
Let us create a new Angular Project.
ng new angmodules
We will use Angular Routing, but Angular CLI does not provide it because it is unnecessary. So, 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, 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.
The next step is to create the three angular components related to the student module. So let us do that.
Step 3: Create Angular Components
We will create the following three angular components related to a student module.
- student.component.ts
- student-list.component.ts
- student-list-item.component.ts
So type the following command to generate the 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. This is because 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 have errors.
ng serve
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, create one file called student.model.ts inside the student folder 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 the publisher starts publishing the values, and eventually, the subscriber gets the data. Please check out this Angular Observables Tutorial With Example article if you are unfamiliar with Observables.
The final step is to prepare all the components to display the data coming from the 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 { }
I have imported the Routes and RouterModule and then created an array of routes and registered them to our angular application.
We need to display the component using the 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 views.
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 outermost component, and inside this component, there is the 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: Student[]) => { 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 the 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 http://localhost:4200/, and you will see something like this after 1 second.
Conclusion
So, 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 to the student will reside on the app >> student folder, and you can create as many modules as you want by separating them to each of that respected folders.
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.
That’s it for this tutorial.
so student-list-item.component.ts is only acting as a presenter?
Thank you for write such a tutorial. this tutorial made me benefit
student.module.ts needs to export some component
@NgModule({
declarations: [StudentComponent, StudentListComponent, StudentListItemComponent],
imports: [
CommonModule
],
exports:[StudentComponent, StudentListComponent]
})
export class StudentModule { }
Thank you
While your article may be good your site isn’t. Using FireFox 73.0.1 64 bit the window won’t stop jumping around long enough for me to read the article.
Even typing this comment was a real PITA.
Thanks Kunal, you helped and clear the myth of feature module while creating project from scratch. Thanks.