banner



How To Create Angular Module

In this tutorial, we will see How To Create Angular Modules To Organize Code. Modules 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. There are many third-party libraries 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 would prepare for your application.

Feature Modules

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

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 theangular.jsonfile.

"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 theappdirectory calleda student, and inside thestudentdirectory, you can see one file calledstudent.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 thisstudent.module.tsfile and not directly inside theapp.module.tsfile 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

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

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 theapp >> studentfolder, and now you can see the student.module.tsfile. This is because all of the three components are automatically imported inside the student.module.tsfile.

// 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 thestudent.module.tsfile inside theapp.module.tsfile.

// 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 calledstudent.model.tsand 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 thestudent.service.tsfile.

// 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 thisstudentsObservable, and the publisher starts publishing the values, and eventually, the subscriber get the data. If you are unfamiliar with Observables, then please check out my this Angular Observables Tutorial With Example article.

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 theapp.module.tsfile.

// 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 routes and register them to our angular application.

Now, we need to display the component by using the router-outletinside theapp.component.htmlfile.

<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 thestudent.component.htmlview. 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 thestudent.component.htmlfile.

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

So this is our outermost component, and inside this component, there is the student-list.component.htmlcomponent.

Now, write the following code inside thestudent-list.component.tsfile.

// 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 thestudent-list.component.htmlfile.

<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 thestudent-list-item.component.htmlfile.

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

Angular Modules Example

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 >> studentfolder, 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 theapp.module.tsfile; you will create one module file respected to your functionality and add your components inside them.

Finally, you can add the module inside theapp.module.tsfile, 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 Example is over.

How To Create Angular Module

Source: https://appdividend.com/2018/12/09/how-to-create-angular-modules-to-organize-code/

Posted by: singhhows2000.blogspot.com

0 Response to "How To Create Angular Module"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel