Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE :: Featured Module in Angular

clock November 1, 2022 08:44 by author Peter

In this article, we are going to discuss the most important feature in the Angular Framework called “Featured Modules”. This article can be accessed by beginners, intermediates, and professionals.


Featured Module
Modules are the most important part of the Angular Application.
Modules are the place where we are grouping components, directives, services, and pipes.
app.module.ts module is a root module of the Angular Application.

Whenever we create a new application, the root module will be added by default.
Let's see the below image to understand the problem first,

Suppose we have a large angular application with thousands of components, directives, services, pipes, etc., and all are maintained in the Root module (“app.module.ts”). In such a scenario, the Root module becomes very mashie and non-maintainable.

What will you do to solve this problem? You will break the root module into small modules and separate it right? So that separated small module is called a “Featured module” in Angular.

Let’s see the below image for more understanding,


In the above image, we have separated “module1”,” module2” and “module3” from the Root module. Each module content component of that module. Eg. Module1 has Component1

Now we have a basic idea of the Featured module, now we will see how many types of featured modules are available in the angular application.

Types of Featured Modules
    Domain - It is based on the application navigation eg. Emp or customer features modules etc
    Routed - All Lazy loaded modules.
    Routing - Routing and its related functionality like Route guard.
    Service - This is related to API request – Response.
    Widget - Widget-related modules which may contain utility, pipes, directives, etc.

Let’s discuss a few important advantages before we will discuss an example of a featured module.

Advantages of the Featured Module
    Code Maintainability
    Scalability
    Lazy Loading
    Abstraction
    Code separation

Now we will create a new angular application and learn feature modules,

Step 1
Create a new Angular Application “ProductDemo”.
ng new "FeaturedDemo"

Step 2
Add two modules “ProductModule” and “PriceModule” components.
ng g m "Product\Product.module"

Above command will create product folder and product module.
Now we will create new module for price. We will use the below command for the same.

ng g m price\price

Price folder and price module will be created.

Step 3 - Create two components for “Product” and “price”.
Now we will add two components for product and price.
ng g c product\product

Product components will be created. Now we will create price component.
ng g c price\price

Price component will be created and added in the price folder.


Step 4 - Configure “ProductModule” and “PriceModule” in the app.module.ts file.
Now we will configure newly added modules in the app.module.ts file.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { PriceModule } from './price/price/price.module';
import { ProductModule } from './product/product/product.module';

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


We have added “ProductModule” and “PriceModule” in the imports array and imported references in the app.module.ts file.

app.module.ts file has “BrowserModule” but other modules have “CommonModule” for common functionalities.

Step 5
Let's see “ProductModule” and “PriceModule”.
Product Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProductComponent } from './product.component';

@NgModule({
  declarations: [
    ProductComponent
  ],
  imports: [
    CommonModule
  ],
  exports:[ProductComponent]
})
export class ProductModule { }


We need to export ProductComponent to export the component. Need to add components to the exports array.

Price Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PriceComponent } from './price.component';

@NgModule({
  declarations: [
    PriceComponent
  ],
  imports: [
    CommonModule
  ],
  exports:[PriceComponent]
})
export class PriceModule { }


Step 6
Add the below code in the “app.component.html” file.
<router-outlet></router-outlet>
<app-price></app-price>
<app-product></app-product>


Now we will execute the angular application and see the results.


That's all for this article. Hope you enjoyed it.



European Visual Studio 2022 Hosting - HostForLIFE :: Three Ways To View Hidden Files In Visual Studio Solution

clock October 26, 2022 10:19 by author Peter

When I thought about this topic, I faintly remembered that I wrote a similar article sometime before.  After searching, I did find the article. But, I will not modify that article, and will write a new one to be parallel with it: .

Introduction
In Visual Studio solution, some files are not readable due to they are not included in the solution. Sometimes, we need to treat these kinds of files as the files included in the solution. This topic is what we will discuss.

The following sections will give three methods to achieve this goal.

    Method 1: Unload project
    Method 2: Switch to Folder View of Visual Studio Explorer
    Method 3: Use Open With

Method 1 - Open Folder in File Explorer from within Visual Studio

Right-click on Solution => Open Folder in File Explorer:

You can Right-click on Project=> Open Folder in File Explorer:

Or, Right-click on a File Folder=> Open Folder in File Explorer:

Click, then you will open the solution, or project, or specific File Folder, such like:

In this way, we can open File Explorer from within Visual Studio, instead of going outside to reopen File Explorer. The shortage is we will lose the Visual Studio environment, such as Source Control or Git from Visual Studio.  In some case, we have installed some third-party Source Control Software may reduce the shortage.

This is an example with TortoiseGit installed:

In this case, even without Visual Studio, we still have user-friendly GUI for Git control.

Method 2 - Show All Files
At the project level, you will have choice to have and Click the Icon Show All Files from the Solution Explorer bar, as shown below:

After Click: all hidden files, that are not included in the solution, will be shown:

Examine one of file, you will see all Git Control feature are available for this file:


In this way, we can manager the hidden files within Visual Studio. The shortage is because they are hidden files, so even after showing, they are still in a plain color, we cannot distinguish if they are in Git Control or not, or if check out or not.

Method 3 - Switch to View Folder
Click the Icon Switch between solutions and available views as shown below


Click the Folder View:


Now we are in Folder View:


In which, we can view all files, including hidden files from the solution, and we will have all editing features, that Visual Studio has. In fact, now Visual Studio somehow is like Visual Studio Code Editor.



AngularJS Hosting Europe - HostForLIFE :: Modules And Controllers In AngularJS

clock October 25, 2022 09:43 by author Peter

In this article, we will see the role of Modules, Controllers, $scope in AngularJS Application. Module: Module in AngularJS application is a container for controllers, directive, filters, services, etc and helps in packaging code as reusable modules.

 
Creating/Defining a Module


The first parameter in angular.module() function is the name of the module and the second parameter is an array in which we can add dependencies. Here, we have not added any external modules/dependencies as we are trying to make this example as simple as possible.
 
Controller
Controller is defined by a JavaScript constructor function. Controller controls and acts as a brain for the View in AngularJS Application. Controller is attached to the DOM using the ng-controller directive. Controllers should only contain business logic.
 
Adding a Controller in our angular module

 

In the above code, we have added a controller with our angular module (i.e. myApp) using Controller method of the module. In Controller method, the first parameter is name of the controller and second is function representing the controller.
 
$scope acts as a glue between application controller and the view. $scope is dynamically injected into controller's function. We have added some data to $scope properties.

Here, we have added our module and controller in View using ng-App and ng-controller directive of AngularJS.
    <!DOCTYPE html>  
    <html xmlns="http://www.w3.org/1999/xhtml">  
    <head>  
        <title>Working with Controller</title>  
        <script src="Script/angular.js"></script>  
        <script>  
            // Declare a module  
            var myApp = angular.module('myApp', []);  
            //Registering a controller in myApp module  
            myApp.controller('myController', function ($scope) {  
                $scope.Name = "Peter Scott";  
                $scope.Website = "www.ittutorialswithexample.com";  
            });  
        </script>  
    </head>  
    <body ng-app="myApp">  
        <div ng-controller="myController">  
            Name:{{Name}}<br />  
            Website:{{Website}}  
        </div>  
    </body>  
    </html>  


Let's save and run the application.

Hope you liked it. Thanks!



AngularJS Hosting Europe - HostForLIFE :: Lazy Loading In Angular With Example

clock October 17, 2022 10:29 by author Peter

In this article, we will see about lazy loading concept in Angular with an example for your understanding.

Lazy loading
Instead of loading all the modules and components in an application it allows only selected module and components to load thus reducing the loading time. Lazy loading feature loads components, modules, and other files of Angular application only when required. This concept is used in complex and larger applications. Lazy loading concept makes an application very fast and uses less memory.

Let us see one example on this lazy loading,

Eg
We will start by creating a new Angular application for easy understanding,

Step 1
Open a command prompt or terminal. Create a new project:
> ng new LazyDemo


make sure to allow routing when creating new project or you can simply use the command : > ng new LazyDemo --routing
> cd LazyDemo

Step 2
Create 3 components or any numbers of your choice just for demo purpose. I'm creating 3 components,
> ng generate component Number1
  ng generate component Number2
  ng generate component Number3

Step 3
Create respective module files in each of the component folders,
> Number1.module.ts
  Number2.module.ts
  Number3.module.ts

Now our file/folder structure will look like this,

Step 4
Create a respective router module file in each component folder,
> Number1-routing.module.ts
  Number2-routing.module.ts
  Number3-routing.module.ts

Step 5
Import the Router Module in the main application module  app.module.ts,
import { AppRoutingModule } from './app-routing.module';

imports: [
  BrowserModule,
  AppRoutingModule
],


Since we have enabled routing at beginning it will be already imported in app.module.ts, In case you forget to apply routing at beginning you can add this, otherwise you can skip this step.

Step 6
Add the code in their own routing modules, Add following code in Number1-routing.module.ts,
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number1Component } from "./number1.component";

const routes: Routes = [
    { path:"", component: Number1Component }
];

@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})

export class Number1RouterModule{}


Here instead of forRoot we called forChild as these are child modules which will be called in app’s main routing module.


The following codes,
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number2Component } from "./number2.component";

const routes: Routes = [
    { path:"", component: Number2Component }
];

@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})

export class Number2RouterModule{}


In Number3-routing.module.ts add the following codes,
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number3Component } from "./number3.component";

const routes: Routes = [
    { path:"", component: Number3Component }
];

@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})

export class Number3RouterModule{}

In Number1.module.ts add following code,
import { NgModule } from "@angular/core";
import { Number1RouterModule } from "./Number1-routing.module";
import { Number1Component } from "./number1.component";

@NgModule({
    declarations:[Number1Component],
    imports:[Number1RouterModule],
    providers: []

})
export class Number1Module{

}


Similarly add same in the other two files Number2.module.ts and Number3.module.ts,
In Number2.module.ts add the following code,
import { NgModule } from "@angular/core";
import { Number2RouterModule } from "./Number2-routing.module";
import { Number2Component } from "./number2.component";

@NgModule({
    declarations:[Number2Component],
    imports:[Number2RouterModule],
    providers: []

})
export class Number1Module{

}


In Number3.module.ts add the following code,
import { NgModule } from "@angular/core";
import { Number3RouterModule } from "./Number3-routing.module";
import { Number3Component } from "./number3.component";

@NgModule({
    declarations:[Number3Component],
    imports:[Number3RouterModule],
    providers: []

})
export class Number3Module{

}


Step 7
Define Routes using loadChildred attribute in app’s main routing module. In main app-routing.module.ts add the following code,
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'number1',
    loadChildren: () => import('../app/number1/Number1.module').then(x => x.Number1Module)
 },
 {
  path: 'number2',
  loadChildren: () => import('../app/number2/Number2.module').then(x => x.Number2Module)
},
{
  path: 'number3',
  loadChildren: () => import('../app/number3/Number3.module').then(x => x.Number3Module)
},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers:[]
})
export class AppRoutingModule { }

For your reference,


We will define child modules in loadChildren attribute defining imports and each independent module’s name and its path.

Step 8
Add routing links to Route HTML page, In app.component.html add the following,
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h2>
    {{ title }}
  </h2>
  <button><a [routerLink]="['/number1']" routerLinkActive="router-link-active" >Number One</a></button><span></span>
  <button><a [routerLink]="['/number2']" routerLinkActive="router-link-active" >Number Two</a></button><span></span>
  <button><a [routerLink]="['/number3']" routerLinkActive="router-link-active" >Number Three</a></button>
</div>
<router-outlet></router-outlet>


Now run the application using ng serve

Output

You can check the working of this lazy loading by inspecting, To do so, press  Ctrl+shift+I. Now under Networks tab you can see the components are not loaded initially.


Now if you click on to Number one component button, that component alone will get loaded,


If you click on Number two component buttton, that component will get loaded,


It actually reduces the memory occupied by loading only the required resources and it is applied in large applications. Components are loaded after we click on the link, they are not loaded on application initialization or app start. I hope this article would be helpful for you with example and simple definitions.

Thank you!



AngularJS Hosting Europe - HostForLIFE :: Lazy Loading In Angular With Example

clock October 17, 2022 10:29 by author Peter

In this article, we will see about lazy loading concept in Angular with an example for your understanding.

 

Lazy loading
Instead of loading all the modules and components in an application it allows only selected module and components to load thus reducing the loading time. Lazy loading feature loads components, modules, and other files of Angular application only when required. This concept is used in complex and larger applications. Lazy loading concept makes an application very fast and uses less memory.

Let us see one example on this lazy loading,

Eg
We will start by creating a new Angular application for easy understanding,

Step 1
Open a command prompt or terminal. Create a new project:
> ng new LazyDemo


make sure to allow routing when creating new project or you can simply use the command : > ng new LazyDemo --routing
> cd LazyDemo

Step 2
Create 3 components or any numbers of your choice just for demo purpose. I'm creating 3 components,
> ng generate component Number1
  ng generate component Number2
  ng generate component Number3

Step 3
Create respective module files in each of the component folders,
> Number1.module.ts
  Number2.module.ts
  Number3.module.ts

Now our file/folder structure will look like this,

Step 4
Create a respective router module file in each component folder,
> Number1-routing.module.ts
  Number2-routing.module.ts
  Number3-routing.module.ts

Step 5
Import the Router Module in the main application module  app.module.ts,
import { AppRoutingModule } from './app-routing.module';

imports: [
  BrowserModule,
  AppRoutingModule
],


Since we have enabled routing at beginning it will be already imported in app.module.ts, In case you forget to apply routing at beginning you can add this, otherwise you can skip this step.

Step 6
Add the code in their own routing modules, Add following code in Number1-routing.module.ts,
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number1Component } from "./number1.component";

const routes: Routes = [
    { path:"", component: Number1Component }
];

@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})

export class Number1RouterModule{}


Here instead of forRoot we called forChild as these are child modules which will be called in app’s main routing module.


The following codes,
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number2Component } from "./number2.component";

const routes: Routes = [
    { path:"", component: Number2Component }
];

@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})

export class Number2RouterModule{}


In Number3-routing.module.ts add the following codes,
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Number3Component } from "./number3.component";

const routes: Routes = [
    { path:"", component: Number3Component }
];

@NgModule({
    exports: [RouterModule],
    imports:[RouterModule.forChild(routes)]
})

export class Number3RouterModule{}

In Number1.module.ts add following code,
import { NgModule } from "@angular/core";
import { Number1RouterModule } from "./Number1-routing.module";
import { Number1Component } from "./number1.component";

@NgModule({
    declarations:[Number1Component],
    imports:[Number1RouterModule],
    providers: []

})
export class Number1Module{

}


Similarly add same in the other two files Number2.module.ts and Number3.module.ts,
In Number2.module.ts add the following code,
import { NgModule } from "@angular/core";
import { Number2RouterModule } from "./Number2-routing.module";
import { Number2Component } from "./number2.component";

@NgModule({
    declarations:[Number2Component],
    imports:[Number2RouterModule],
    providers: []

})
export class Number1Module{

}


In Number3.module.ts add the following code,
import { NgModule } from "@angular/core";
import { Number3RouterModule } from "./Number3-routing.module";
import { Number3Component } from "./number3.component";

@NgModule({
    declarations:[Number3Component],
    imports:[Number3RouterModule],
    providers: []

})
export class Number3Module{

}


Step 7
Define Routes using loadChildred attribute in app’s main routing module. In main app-routing.module.ts add the following code,
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'number1',
    loadChildren: () => import('../app/number1/Number1.module').then(x => x.Number1Module)
 },
 {
  path: 'number2',
  loadChildren: () => import('../app/number2/Number2.module').then(x => x.Number2Module)
},
{
  path: 'number3',
  loadChildren: () => import('../app/number3/Number3.module').then(x => x.Number3Module)
},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers:[]
})
export class AppRoutingModule { }

For your reference,


We will define child modules in loadChildren attribute defining imports and each independent module’s name and its path.

Step 8
Add routing links to Route HTML page, In app.component.html add the following,
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h2>
    {{ title }}
  </h2>
  <button><a [routerLink]="['/number1']" routerLinkActive="router-link-active" >Number One</a></button><span></span>
  <button><a [routerLink]="['/number2']" routerLinkActive="router-link-active" >Number Two</a></button><span></span>
  <button><a [routerLink]="['/number3']" routerLinkActive="router-link-active" >Number Three</a></button>
</div>
<router-outlet></router-outlet>


Now run the application using ng serve

Output

You can check the working of this lazy loading by inspecting, To do so, press  Ctrl+shift+I. Now under Networks tab you can see the components are not loaded initially.


Now if you click on to Number one component button, that component alone will get loaded,


If you click on Number two component buttton, that component will get loaded,


It actually reduces the memory occupied by loading only the required resources and it is applied in large applications. Components are loaded after we click on the link, they are not loaded on application initialization or app start. I hope this article would be helpful for you with example and simple definitions.

Thank you!



AngularJS Hosting Europe - HostForLIFE :: Angular - Promises Vs Observables

clock October 7, 2022 09:58 by author Peter

In this article, we are going to discuss the differences between Promises and Observable in angular programming. This article can be used by beginners, intermediates, and professionals.


We are going to cover,
    Sync and Async
    Promises vs Observables

Prerequisite
    Basic knowledge of Angular
    Basic knowledge of Promises and Observables.

Promises and Observables
We should understand Sync and Async first before we start on promises or observables.

In simple words,
Sync – Thread will wait for a response.
Async - The thread will request data in the background and the main thread will not wait for a response.

It means,
Sync code is blocking in nature hence Async programming comes in to picture.
Async programming is non-blocking and executes in the background without blocking the main thread.

Now a question comes in the mind, how will we have handled Async operations in Angular?
The answer would be using Promises or Observables.

Async operations can be handled in Angular either using promises or observables.
Now another question comes raised, what is the difference between them and when should we use what?

Differences between Promises and Observables
    Promise provides the data once data will be ready. While Observables provides data in chunks.
    Promise provide data whether someone is using it or not, but observables provide data only if someone request/subscribe to it.
    A promise is native to JavaScript. Observables are part of RxJs not JavaScript.
    A promise can emit only a single value while an observable can return multiple values.
    Promise can’t cancel once created. Observables can be canceled using unsubscribe.
    Promises don’t have operators. Observables provided operators like maps, filters, reduce, and retry, which are useful for complex scenarios.
    Promises are eager. Observables are Lazy.

I hope you enjoy this article and find it useful.



AngularJS Hosting Europe - HostForLIFE :: Update Angular For Environment And Project

clock October 3, 2022 12:18 by author Peter

A - Introduction
We need to realize that updating Angular CLI for environment, or say, globally, and for a specific project or application, or say locally are different.  We will discuss them in this article respectively.

This is the content of this article:

    A - Introduction
    B - Update Angular for Environment
    C - Angular Global Update will not Affect Individual Project
    D - Update Angular for Project
    E - Update Angular for Project: Sample

B - Update Angular for Environment
In order to update the angular-cli package installed globally in your system, you need to run:
    npm uninstall -g @angular/cli
    npm install -g @angular/cli@latest


Step 1: Check the Current Version
Open a window console, type command to view the installed Angular version:
ng v

Step 2: Uninstall Angular globally
We see the current installed Angular version is 12.2.17, uninstall the Angular CLI globally by
npm uninstall -g @angular/cli

Step 3: Install Angular Globally
After uninstalling, check the angular version again by ng v, You will see the system has not recognized the ng command anymore. Reinstall Angular globally by
npm install -g @angular/cli@latest

Step 4: Check the Angular version again, by ng v:

Now, the environment has been updated to Angular V 14.2.3, the current version.

C - Angular Global Update will not Affect Individual Project
However, the global Angular update will not affect project, or local, Angular version. For example, we have a project with version 11.1.2, while the global Angular CLI version is 12.2.0, as shown below, when we run command:

Step 1: Check the current project Angular Version and the Environment Angular Version (global)
Run the version check command in the project folder:

ng v

We can see the Angular version for the project is 11.1.2, while the environment, global, is 12.2.6.

Step 2: Uninstall the current Angular Version
npm uninstall -g @angular/cli

Angular is uninstalled globally, when we run the command ng v to check Angular version, the ng command is not recognized:

The local version in the project is uninstalled, too:

\

Step 3: Reinstall Angular Globally
We run the global update command from this project folder:
npm install -g @angular/cli@latest

Step 4: Check Angular version
Outside of the project, we have the global version as 14.2.4:


while the local version is still kept the same as version 11.1.2


i.e., the uninstall/install command does not work for an existing Angular Project

D - Update Angular for Project
For Angular project update, we need to use update command, instead of uninstall/install commands:  

Get Update from Angular Update Guide
Starting from Angular 6, the process of upgrading or updating the Angular apps to the latest version has become very easy. You can follow this Angular Update Guide step by step:
    Choose the Current version Angular and the version you wish to upgrade
    Select the App Complexity as Advanced
    Choose other dependencies
    Choose your package manager
    Click on Show me how to update

The above gives the detailed steps needed to update Angular to the latest version. The list contains three sections. Before Update, During the update, After update. All you needed to do is follow those steps. Get Update Angular Update Guide Following the Compiler Instruction:

We can get the same from another approach:
In some case, for example, when we get a project from DevOps Server or GitHub Server, or we switch the project from different branch of git, when we try to run the project, we get this error:

After running npm install to get the packages sometimes we got the issue resolved, sometimes, we might get a notice to update our local Angular Version:


Check the version,


The project Angular version is 11.1.2 while the global version is 14.2.2:
Now, we need to update the Angular for this project from Version 11.1.2 to 14, we follow the instruction from Angular Notice (in green frame)


Follow the link: https://update.angular.io/, choose the correct version, here from 11 to 14:


We got these suggestions:


E - Update Angular for Project: Sample
Following the instruction, we update the Project Angular CLI step by step:
Step 1: update Angular from version 11 to 12:


Command failed.
Follow the instruction, and rerun the command with "--force":

 

Command successes. Check the version:


The Project Angular CLI version has been updated to V 12. Before we update it to V 13, follow the instruction, we should check if the TypeScript version and the Node.js Version are satisfied for the requirement:


Check TypeScript and Node.js versions:

They are good, then we move to the next step,
Step 2: update Angular from version 12 to 13:

We got difficulty: Repository is not clean:

that was caused by we updated local Angular CLI version from 11 to 12,

Note
Look at the changed files inside, we can know what changes we have made,


This is the update of package.json that indicates the Angular components versions from 11 updated to 12, while the TepyScript version from 4.1.2 to 4.3.5.

the file, angular,.json indicates, for Angular 11, aot is set as true by default, while in Angular 12, this default choice even disappeared. This indicates the fact:

    AOT --- Ahead-of-time (AOT) compilation
        Although it was introduced in Version 8 as a choice, such as with the command ng build --prod
        By default since Version 9, set "aot": true in angular.json file;
        In version 12, JIT will be deprecated associated with View Engine

Save them to git,

Rerun

Step 3: update Angular from version 13 to 14:
Finally, we got:

Run the project:

We have done the Project Angular Update process.



Node.js Hosting Europe - HostForLIFE ::Middleware In Node.js

clock September 27, 2022 09:10 by author Peter

What is middleware and how to use middleware in node.js with express.js
Middleware is a piece of code (function) that is used to execute some code after the server gets a call from a client and before the controller action which will send a response. So it means that whenever a client will call an API, before reaching the request to that API (route), middleware code will be executed.


Middleware is used for different purposes like logging requests, and verifying requests for some specific requirement. Like in this article, we will be using middleware to verify if some specific key is present in the request headers or not.

Creating a Node server using express.js
For creating a node.js server, go to a folder and open vscode in it. Run the command npm init to initialize the node.js project. It will create a package.json file in your root directory. Then command npm install express to install express.js which we will use to create our server.

Optionally, run the command npm install nodemon this will install nodemon in your project. Nodemon is used to auto-refresh your node.js project without starting the server again and again.

In the package.json file, update the scripts tag as follows:
//if nodemon is installed
"scripts": {
        "start": "nodemon index.js"
},
//if nodemon is not installed
"scripts": {
        "start": "node index.js"
},

Then in your root directory, create a file app.js and add the following code to it.
const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.send("Home Page");
});

app.get("/users", (req, res) => {
  res.send("Users Page");
});

app.listen(3000, () => console.log(`Server is started at port 3000`));


Creating the middleware
In node.js, middleware has three parameters req, res, and next. Next is very important here. When we process our logic in the middleware then at the end we have to call next() so that call can react to the desired route.

We will be creating a middleware that will check every request and verify if some specific key (some-key in our case) is present in the header or not. If a key is there, then it will pass the request to the route otherwise it will reject the call and send the response that the request is invalid.

Create a folder with the name middleware (you can give any name but the code I am using for this article have this name) and add a file middleware.js in it. Then add the following code in the file.
function headersVerificationMiddleware(req, res, next) {
  if (!req.headers["some-key"]) {
    console.log("Invalid request");
    res.send("Invalid request");
  }
  console.log("Inside Middleware");
  next();
}


module.exports = headersVerificationMiddleware;

Then update your app.js code according to the following code.
const express = require("express");
const app = express();

//adding middleware
const headersVerificationMiddleware = require("./middleware");
app.use(headersVerificationMiddleware);

app.get("/", (req, res) => {
  res.send("Home Page");
});

app.get("/users", (req, res) => {
  res.send("Users Page");
});

app.listen(3000, () => console.log(`Server is started at port 3000`));


Output without passing the some-key in HTTP headers.


Output with some-key in HTTP headers

Some key points about Middlewares
 
1. Middlewares are similar to controller actions (routes)
Controller actions which have req, and res variables are similar to middleware. The only difference is that middleware also has a variable next which will be called at the end of middleware. It is not necessary for the next() method to be called at the end of the middleware method. It can be used anywhere in the middleware where the next route needs to be called.

2. Middleware work in order
Middleware work in the same order in which they are defined in the app.js file. For example, there are two middleware MiddlewareA and MiddlewareB these both will be called in order. First MiddlewareA will be executed and then MiddlewareB will be executed.



AngularJS Hosting Europe - HostForLIFE :: Angular Standards And Best Practices

clock September 22, 2022 10:14 by author Peter

Angular is a TypeScript-based free and open-source web application framework.
Best Practices of Angular Development


1. Avoid ‘any’ type
A type-checking language is Typescript. However, there may be other situations, such as when we require dynamic content or when we are unsure of the precise data type of some variables. In these circumstances, we can notify typescript that the variable can be of any type by using the data type 'any'.

But it's not a smart idea to always use "any." Any instructs the typescript to bypass type checking. This could put your code at risk of costly, hard-to-trace, and hard-to-debug problems.

const number_1: any = 1;
const number_2: any = 3;
const string_1: any = ‘a’;
const number_3: any = number_1 + number_2;
console.log(`Value of number_3 is:’, number_3);

// Output
Value of number_3 is 13


How we can overcome this by defining its type as mentioned below
const number_1: number = 1;
const number_2: number = 3;
const string_1: string = ‘a’;
const number_3: number = number_1 + number_2;
console.log(`Value of number_3 is:’, number_3);

// Output
Value of number_3 is 13


If we give the wrong type to any costant than we get the compile time error
const number_1: number = 1;
const string_1: number = ‘a’;
// This will give a compile error saying:
error TS2322: Type 'string'
is not assignable to type 'number'.
const string_1: number


2. Use Features of ES6
ES6 stands for ECMAScript 6, which offers new capabilities and syntax to create code that is more contemporary and understandable. It is always being updated with new features and functionality. JavaScript programming is made simpler with ES6 features like Let and Const, Arrow Functions, and string interpolation.

3. Use trackBy along with ngFor
An angular application that uses simply the *ngFor directive without the trackBy function will destroy all of the DOM elements and then reconstruct them in the DOM tree. Therefore, even when the same data is being used, having a lot of data will cause the programme to perform slowly. The trackBy and *ngFor directives should be used together because of this.

In Component.ts
trackByUserCode(index: number, user: any): string {
return user.code;
}

In Component.html

*ngFor='let user of users; trackBy:trackByUserCode'>


4. Use Lazy Loading
The process of loading various modules, such as documents, JS, CSS, videos, photos, etc., is known as lazy loading. By splitting the application's load time into several packets and loading them as needed, it accelerates application load time. Lazy loading can be helpful when loading a large application rather than utilising other functions to load the modules.

When anything is used, lazy loading only loads it. Instead of loading the component as specified in the AppRoutingModule routes settings, we can just use the lazy-loading function to loadChildren. One of the best angular practises is to lazy load or load a certain app feature when needed rather than when the app launches.
const routes: Routes = [{
path: 'users',
loadChildren: () => import('./modules/users/user.module').then(m => m.UserModule)
}];


5. Prevent Memory Leaks in Angular Observable
The first component is removed and the second component is initialised when we move from one component to the next. The initial component, which had subscribed to the Observable, has now been removed. This can result in memory leaks.

We can prevent this by following techniques

1. Using takeUntil()
TakeUntil monitors second Observables, and when the value of the observables is generated, it will dispose the subscription and the cycle will be complete.

this.authService.GetUserList()
  .pipe(takeUntil(this.ngUnsubscribe))
  .subscribe(res => {this.userList = res;});
...
...
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}


2. Using the Async pipe
It returns to the most recent value that was emitted after subscribing to an Observable or Promise.

*ngFor="let item of userService.GetUserList() | async";
{{item.userName}}


3. Using take(1)
It makes sure that you’re getting the data only once.

this.userService.GetUserList()
  .pipe(take(1))
  .subscribe(res = {this.userList = res;})


6. Avoid logic in templates
All template-related business logic can be isolated into a component even when the function calls in angular templates are technically correct. It helps with unit testing and also cuts down on issues in the event that a template change occurs in the future.

7. Declare Safe Datatypes
The first step will be to confirm the categories of data and the range of values it contains. Following that, the variable will only accept the possible values. We can declare a variable as a list of potential values or a different type instead of declaring it as a variable of a specific type.

Example
type Roles = "Admin" | "User";
const user1: Roles = "Admin";
const user2: Roles = "User";
const user3: Roles = "Teacher";


// The last line will give this error: Type ‘"Teacher"’ is not assignable to type 'Roles'.

8. User CDK Virtual Scroll
CDK (Component Development Kit) To present lengthy lists of components more effectively, utilise Virtual Scroll. By setting the container element's height to be the same as the sum of all the elements' heights, virtual scrolling makes it possible to simulate all values effectively.

9. Use Environment Variables
For all types of contexts, Angular provides various environment setups to declare individual variables. Angular environments for development and production are standard. We can even add new environments or variables to the environment files that already exist.

10. Use Lint Rules
The tslint provides a number of built-in parameters that can be customised in the tslint.json file, including no-any, no-console, no-magic-numbers, etc. The programme is forced to be better and more reliable as a result. You can configure it with your own lint rules and settings. This guarantees the clarity and coherence of our code.

11. Maintain proper folder structures
Before beginning any angular project, everyone should take into account the importance of creating and maintaining a correct folder structure. Throughout development, the folder structure should be adaptable to new developments.

12. Break large components into small reusable components.
It can also be seen as a development principle with a single responsibility. It is challenging to manage, test, and debug huge components. Reduce code duplication and make it simpler to manage, maintain, and debug the component by breaking it up into smaller, more reusable components if it grows in size.

13. State Management
One of the most challenging areas of software development is state management. By saving the state of any sort of data, Angular's state management facilitates the handling of state transitions.

NGRX, NGXS, Akita, and other state management libraries for Angular are available on the market, and each of them serves a different purpose. The ideal state management for our application can be chosen before it is put into use.

Some of the advantages of utilizing state management.

It allows data to be shared between multiple components.
It allows for centralized state transition control.
The code will be cleaner and easier to read.
It’s simple to troubleshoot when something goes wrong.
There are development tools that are available for tracing and debugging in state management libraries.

14. Documentation in code
Code documentation is a wise move. It will help a new developer to comprehend the project's logic and readability. A smart Angular practise is to document each variable and method.

The actual task that a method performs must be specified
/**
* This is the get function
* @param age This is the age parameter
* @returns returns a string version of age
*/
function getUserAge(age: number): string {
return age.toString();
}


in multi-line comments that accompany each method definition.

15. Single Responsibility Principle
Instead of grouping them all under a single ts file, it is preferable to make distinct ts files for components, templates, styles, and services. You can write clear, readable, and maintainable code if you treat each file as if it is responsible for a single functionality.

16. Using Interfaces
Whenever we are drafting a contract for our class, we must employ interfaces. By utilising them, we can compel the class to implement the attributes and functions stated in the interface. The best example of this is when your component has angular lifecycle hooks:

The HomeComponent class implements OnInit and OnDestroy.

Interfaces are the best technique to accurately describe the declared objects.

TypeScript will produce an error, enable IntelliSense for us, and begin populating an object if it does not include the properties of the interface:

export interface User {
id: number;
name: string;
email: string;
class: number;
gender: "male" | "female";
stream : "ECE" | "CSE" | "IT";
status: boolean;
}

17. Change Detection Optimisations.
Instead of hiding non-visible DOM components with CSS, it's a good idea to remove them from the DOM using *ngIf.
Transfer difficult computations into the ngDoCheck lifecycle hook to make your expressions faster.
Calculations that are complex should be cached for as long as possible.
Use the OnPush change detection method to tell Angular that no changes have been made. You are then able to bypass the entire change detection procedure.

18. Using Smart – Dumb components / Use Smart – Dumb Components Technique
By informing Angular that the dumb components have not changed, this solution makes it easier to employ the OnPush change detection mechanism. Smart components are employed for processing data through API calls, concentrating on functionality, and managing states. They are more concerned with how they appear than the dumb components, who are only interested in appearances.

I would greatly appreciate it if you would support me by subscribe the channel if have you enjoyed this post and found it useful. Thank you in advance.



AngularJS Hosting Europe - HostForLIFE :: Easily Use MockAPI.io With Angular 14

clock September 19, 2022 08:54 by author Peter

MockAPI (https://mockapi.io/) is a simple tool that lets you easily mockup APIs, generate custom data, and perform operations on it using RESTful interface. We can consume these API endpoints in our Angular 14 application to test the flow without actual Web APIs. 

Create an account in MockAPI.io

It is amazingly easy to create a new account in MockAPI.MockAPI gives various flexible plans. In the free plan, we can create one Project and four resources in that project. In the $5/month plan, we can create 20 projects and 50 resources per project. If you are ready to buy a yearly plan, you will get 20 projects plan at $35. 

For testing purposes, we can choose a Free plan.  We can create a new Project in this free plan.


We can give a valid project name. It is mandatory. Also, we can give an optional API prefix as well.  Please note that we can create up to four resources in a project in Free plan. After creating the project, we can click on the project name, and it will allow us to create resources. We can click on the New Resource button as well. It will open a new popup window and we can give resource details here.  

We are going to create an employee management application and will see all the CRUD operations using MockAPI. Hence, we can create the resource with a specific employee model. Please note that each resource must start with an id property. You can add multiple properties as per your requirements.  

Currently MockAPI supports seven types of properties. 


We can create the employee resource with the following properties.


Each resource will support the below CRUD methods. 


You can see a unique API endpoint for each project. 

 

If you click the Generate All button, it will create 50 employee sample records automatically. We can also add more employee records by clicking the employee resource button. Please note that Free plan will support a maximum of 100 records per resource.  

You can use the Reset All button to clear all mock data.  

We can use the Data button to view all data for a particular resource. We can use the Edit button to add or remove properties from a resource. The Delete button will remove entire resources from the project.  

We can create an Angular 14 project and consume these API endpoints easily. We will see all the CRUD actions using our Angular 14 project.  

Create Angular 14 project using Angular CLI

We can use the CLI command below to create a new Angular project.

ng new Angular14MockAPI

Choose the routing option as Yes and stylesheet format as CSS.

Add bootstrap and font-awesome libraries to the project.

npm install bootstrap font-awesome   

We must change “styles.css” file in the root folder with below changes to access these packages globally in the application without further references.  

styles.css
@import "~bootstrap/dist/css/bootstrap.css";
@import "~font-awesome/css/font-awesome.css";


Create an environment variable inside environment class for baseUrl. This will be used across the application.  

environment.ts
export const environment = {
  production: false,
  baseUrl: 'https://63261f0eba4a9c4753234af7.mockapi.io/'
};


Copy the API endpoint value from MockAPI and give it as baseUrl in environment file.
Create an employee interface now.  

ng g class employee\employee  

Use the below code.

employee.ts
export interface Employee {
    id: string,
    name: string,
    address: string,
    company: string,
    designation: string,
    cityname: string
}


Create an employee service now.  
ng g service employee\employee  

Use the below code.

employee.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { Employee } from './employee';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  private employeesUrl = environment.baseUrl + 'api/employee';

  constructor(private http: HttpClient) { }

  getEmployees(): Observable<Employee[]> {
    return this.http.get<Employee[]>(this.employeesUrl)
      .pipe(
        catchError(this.handleError)
      );
  }

  getEmployee(id: string | null): Observable<Employee> {
    if (id === '') {
      return of(this.initializeEmployee());
    }
    const url = `${this.employeesUrl}/${id}`;
    return this.http.get<Employee>(url)
      .pipe(
        catchError(this.handleError)
      );
  }

  createEmployee(employee: Employee): Observable<Employee> {
    employee.id = '';
    return this.http.post<Employee>(this.employeesUrl, employee)
      .pipe(
        catchError(this.handleError)
      );
  }

  deleteEmployee(id: string): Observable<{}> {
    const url = `${this.employeesUrl}/${id}`;
    return this.http.delete<Employee>(url)
      .pipe(
        catchError(this.handleError)
      );
  }

  updateEmployee(employee: Employee): Observable<Employee> {
    const url = `${this.employeesUrl}/${employee.id}`;
    return this.http.put<Employee>(url, employee)
      .pipe(
        map(() => employee),
        catchError(this.handleError)
      );
  }

  private handleError(err: any) {
    let errorMessage: string;
    if (err.error instanceof ErrorEvent) {
      errorMessage = `An error occurred: ${err.error.message}`;
    } else {
      errorMessage = `Backend returned code ${err.status}: ${err.body.error}`;
    }
    console.error(err);
    return throwError(() => errorMessage);
  }

  private initializeEmployee(): Employee {
    return {
      id: "",
      name: "",
      address: "",
      company: "",
      designation: "",
      cityname: ""
    };
  }
}


We can create a Loader service for entire application. This service can be used for showing a loader while the application is accessing the backend MockAPI.

ng g service loader

Copy the below code.

loader.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

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

  controlLoader!: Subject<boolean>;
  constructor() {
    this.controlLoader = new Subject<boolean>();
  }

  show() {
    this.controlLoader.next(true);
  }

  hide() {
    this.controlLoader.next(false);
  }
}


Add the modules below to the AppModule class.

    ReactiveFormsModule
    FormsModule
    HttpClientModule

We can create an employee list component. This component will be used to display all the employee information. This component is also used to edit and remove employee data.  

ng g component employee\EmployeeList  

Change the class file with the code below.  

employee-list.component.ts
import { Component, OnInit } from '@angular/core';
import { LoaderService } from 'src/app/loader.service';
import { Employee } from '../employee';
import { EmployeeService } from '../employee.service';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
  pageTitle = 'Employee List';
  filteredEmployees: Employee[] = [];
  employees: Employee[] = [];
  errorMessage = '';

  _listFilter = '';
  get listFilter(): string {
    return this._listFilter;
  }
  set listFilter(value: string) {
    this._listFilter = value;
    this.filteredEmployees = this.listFilter ? this.performFilter(this.listFilter) : this.employees;
  }

  constructor(private employeeService: EmployeeService, private loader: LoaderService) { }

  performFilter(filterBy: string): Employee[] {
    filterBy = filterBy.toLocaleLowerCase();
    return this.employees.filter((employee: Employee) =>
      employee.name.toLocaleLowerCase().indexOf(filterBy) !== -1);
  }

  ngOnInit(): void {
    this.getEmployeeData();
  }

  getEmployeeData() {
    this.loader.show();
    this.employeeService.getEmployees()
      .subscribe({
        next: (employees) => {
          this.employees = employees;
          this.filteredEmployees = employees;
        },
        error: (err) => {
          this.errorMessage = <any>err;
          this.loader.hide();
        },
        complete: () => {
          console.info('Get employees in employee list');
          this.loader.hide();
        }
      });
  }

  deleteEmployee(id: string, name: string): void {
    if (id === '') {
      this.onSaveComplete();
    } else {
      if (confirm(`Are you sure want to delete this Employee: ${name}?`)) {
        this.loader.show();
        this.employeeService.deleteEmployee(id)
          .subscribe({
            next: () => this.onSaveComplete(),
            error: (err) => {
              this.errorMessage = <any>err;
              this.loader.hide();
            },
            complete: () => {
              console.info('Delete employee in employee list');
              this.loader.hide();
            }
          });
      }
    }
  }

  onSaveComplete(): void {
    this.employeeService.getEmployees()
      .subscribe({
        next: (employees) => {
          this.employees = employees;
          this.filteredEmployees = employees;
        },
        error: (err) => this.errorMessage = <any>err,
        complete: () => console.info('Get employees in employee list')
      });
  }
}

We can change the template and style files also.  

employee-list.component.html
<div class="card">
    <div class="card-header">
        {{pageTitle}}
    </div>
    <div class="card-body">
        <div class="row" style="margin-bottom:15px;">
            <div class="col-md-2">Filter by:</div>
            <div class="col-md-4">
                <input type="text" [(ngModel)]="listFilter" />
            </div>
            <div class="col-md-2"></div>
            <div class="col-md-4">
                <button class="btn btn-primary mr-3" [routerLink]="['/employees/0/edit']">
                    New Employee
                </button>
            </div>
        </div>
        <div class="row" *ngIf="listFilter">
            <div class="col-md-6">
                <h4>Filtered by: {{listFilter}}</h4>
            </div>
        </div>
        <div class="table-responsive">
            <table class="table mb-0" *ngIf="employees && employees.length">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Address</th>
                        <th>Company</th>
                        <th>Designation</th>
                        <th></th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let employee of filteredEmployees">
                        <td>
                            <a [routerLink]="['/employees', employee.id]">
                                {{ employee.name }}
                            </a>
                        </td>
                        <td>{{ employee.address }}</td>
                        <td>{{ employee.company }}</td>
                        <td>{{ employee.designation}} </td>
                        <td>
                            <button class="btn btn-outline-primary btn-sm"
                                [routerLink]="['/employees', employee.id, 'edit']">
                                Edit
                            </button>
                        </td>
                        <td>
                            <button class="btn btn-outline-warning btn-sm"
                                (click)="deleteEmployee(employee.id,employee.name);">
                                Delete
                            </button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
<div *ngIf="errorMessage" class="alert alert-danger">
    Error: {{ errorMessage }}
</div>

Change the stylesheet as well.

employee-list.component.css   

thead {
    color: #337AB7;
}


We can create employee edit component with the below command  

ng g component employee\EmployeeEdit  

Modify the class file with the code below.  

employee-edit.component.ts
import { Component, OnInit, OnDestroy, ElementRef, ViewChildren } from '@angular/core';
import { FormControlName, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Subscription } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { Employee } from '../employee';
import { EmployeeService } from '../employee.service';
import { LoaderService } from 'src/app/loader.service';

@Component({
  selector: 'app-employee-edit',
  templateUrl: './employee-edit.component.html',
  styleUrls: ['./employee-edit.component.css']
})
export class EmployeeEditComponent implements OnInit, OnDestroy {
  @ViewChildren(FormControlName, { read: ElementRef }) formInputElements!: ElementRef[];
  pageTitle = 'Employee Edit';
  errorMessage!: string;
  employeeForm!: FormGroup;
  tranMode!: string;
  employee!: Employee;
  private sub!: Subscription;

  displayMessage: { [key: string]: string } = {};
  private validationMessages: { [key: string]: { [key: string]: string } };

  constructor(private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private employeeService: EmployeeService,
    private loader: LoaderService) {

    this.validationMessages = {
      name: {
        required: 'Employee name is required.',
        minlength: 'Employee name must be at least three characters.',
        maxlength: 'Employee name cannot exceed 50 characters.'
      },
      cityname: {
        required: 'Employee city name is required.',
      }
    };
  }

  ngOnInit() {
    this.tranMode = "new";
    this.employeeForm = this.fb.group({
      name: ['', [Validators.required,
      Validators.minLength(3),
      Validators.maxLength(50)
      ]],
      address: '',
      cityname: ['', [Validators.required]],
      company: '',
      designation: '',
    });

    this.sub = this.route.paramMap.subscribe(
      params => {
        const id = params.get('id');
        const cityname = params.get('cityname');
        if (id == '0') {
          const employee: Employee = { id: "0", name: "", address: "", company: "", designation: "", cityname: "" };
          this.displayEmployee(employee);
        }
        else {
          this.getEmployee(id);
        }
      }
    );
  }

  ngOnDestroy(): void {
    this.sub.unsubscribe();
  }

  getEmployee(id: string | null): void {
    this.loader.show();
    this.employeeService.getEmployee(id)
      .subscribe({
        next: (employee: Employee) => this.displayEmployee(employee),
        error: (err) => {
          this.errorMessage = <any>err;
          this.loader.hide();
        },
        complete: () => {
          console.info('Get employee in employee edit');
          this.loader.hide();
        }
      });
  }

  displayEmployee(employee: Employee): void {
    if (this.employeeForm) {
      this.employeeForm.reset();
    }
    this.employee = employee;
    if (this.employee.id == '0') {
      this.pageTitle = 'Add Employee';
    } else {
      this.pageTitle = `Edit Employee: ${this.employee.name}`;
    }
    this.employeeForm.patchValue({
      name: this.employee.name,
      address: this.employee.address,
      company: this.employee.company,
      designation: this.employee.designation,
      cityname: this.employee.cityname
    });
  }

  deleteEmployee(): void {
    if (this.employee.id == '0') {
      this.onSaveComplete();
    } else {
      if (confirm(`Are you sure want to delete this Employee: ${this.employee.name}?`)) {
        this.loader.show();
        this.employeeService.deleteEmployee(this.employee.id)
          .subscribe({
            next: () => this.onSaveComplete(),
            error: (err) => {
              this.errorMessage = <any>err;
              this.loader.hide();
            },
            complete: () => {
              console.info('Delete employee in employee edit');
              this.loader.hide();
            }
          });
      }
    }
  }

  saveEmployee(): void {
    if (this.employeeForm.valid) {
      if (this.employeeForm.dirty) {
        const e = { ...this.employee, ...this.employeeForm.value };
        if (e.id === '0') {
          this.loader.show();
          this.employeeService.createEmployee(e)
            .subscribe({
              next: () => this.onSaveComplete(),
              error: (err) => {
                this.errorMessage = <any>err;
                this.loader.hide();
              },
              complete: () => {
                console.info('Create employee in employee edit');
                this.loader.hide();
              }
            });
        } else {
          this.loader.show();
          this.employeeService.updateEmployee(e)
            .subscribe({
              next: () => this.onSaveComplete(),
              error: (err) => {
                this.errorMessage = <any>err;
                this.loader.hide();
              },
              complete: () => {
                console.info('Update employee in employee edit');
                this.loader.hide();
              }
            });
        }
      } else {
        this.onSaveComplete();
      }
    } else {
      this.errorMessage = 'Please correct the validation errors.';
    }
  }

  onSaveComplete(): void {
    this.employeeForm.reset();
    this.router.navigate(['/employees']);
  }
}

We can change the template file also.  

employee-edit.component.html
<div class="card">
    <div class="card-header">
      {{pageTitle}}
    </div>

    <div class="card-body">
      <form novalidate (ngSubmit)="saveEmployee()" [formGroup]="employeeForm">

        <div class="form-group row mb-2">
          <label class="col-md-3 col-form-label" for="employeeNameId">Employee Name</label>
          <div class="col-md-7">
            <input class="form-control" id="employeeNameId" type="text" placeholder="Name (required)"
              formControlName="name" />
          </div>
        </div>

        <div class="form-group row mb-2">
          <label class="col-md-3 col-form-label" for="citynameId">City</label>
          <div class="col-md-7">
            <input class="form-control" id="citynameid" type="text" placeholder="Cityname (required)"
              formControlName="cityname" />
          </div>
        </div>

        <div class="form-group row mb-2">
          <label class="col-md-3 col-form-label" for="addressId">Address</label>
          <div class="col-md-7">
            <input class="form-control" id="addressId" type="text" placeholder="Address" formControlName="address" />
          </div>
        </div>

        <div class="form-group row mb-2">
          <label class="col-md-3 col-form-label" for="companyId">Company</label>
          <div class="col-md-7">
            <input class="form-control" id="companyId" type="text" placeholder="Company" formControlName="company" />
          </div>
        </div>

        <div class="form-group row mb-2">
          <label class="col-md-3 col-form-label" for="designationId">Designation</label>
          <div class="col-md-7">
            <input class="form-control" id="designationId" type="text" placeholder="Designation"
              formControlName="designation" />
          </div>
        </div>

        <div class="form-group row mb-2">
          <div class="offset-md-2 col-md-6">
            <button class="btn btn-primary" style="width:80px;margin-right:10px;" type="submit"
              [title]="employeeForm.valid ? 'Save your entered data' : 'Disabled until the form data is valid'"
              [disabled]="!employeeForm.valid">
              Save
            </button>
            <button class="btn btn-outline-secondary" style="width:80px;margin-right:10px;" type="button"
              title="Cancel your edits" [routerLink]="['/employees']">
              Cancel
            </button>
            <button class="btn btn-outline-warning" *ngIf="pageTitle != 'Add Employee'"
              style="width:80px;margin-right:10px" type="button" title="Delete this product" (click)="deleteEmployee()">
              Delete
            </button>
          </div>
        </div>
      </form>
    </div>

    <div class="alert alert-danger" *ngIf="errorMessage">{{errorMessage}}
    </div>
  </div>


We need one more component to display the employee details in a separate window. We can create now.  

ng g component employee\EmployeeDetail  


We can change the class file with the code below.  

employee-detail.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { LoaderService } from 'src/app/loader.service';
import { Employee } from '../employee';
import { EmployeeService } from '../employee.service';

@Component({
  selector: 'app-employee-detail',
  templateUrl: './employee-detail.component.html',
  styleUrls: ['./employee-detail.component.css']
})
export class EmployeeDetailComponent implements OnInit {
  pageTitle = 'Employee Detail';
  errorMessage = '';
  employee: Employee | undefined;

  constructor(private route: ActivatedRoute,
    private router: Router,
    private employeeService: EmployeeService,
    private loader:LoaderService) { }

  ngOnInit() {
    const id = this.route.snapshot.paramMap.get('id');
    if (id) {
      this.getEmployee(id);
    }
  }

  getEmployee(id: string) {
    this.loader.show();
    this.employeeService.getEmployee(id)
      .subscribe({
        next: (employee) => this.employee = employee,
        error: (err) => {
          this.errorMessage = <any>err;
          this.loader.hide();
        },
        complete: () => {
          console.info('Get employee in employee details');
          this.loader.hide();
        }
      });
  }

  onBack(): void {
    this.router.navigate(['/employees']);
  }
}

Modify the template file with the code below.  

employee-detail.component.html
<div class="card">
    <div class="card-header"
         *ngIf="employee">
      {{pageTitle + ": " + employee.name}}
    </div>
    <div class="card-body"
         *ngIf="employee">
      <div class="row">
        <div class="col-md-8">
          <div class="row">
            <div class="col-md-3">Name:</div>
            <div class="col-md-6">{{employee.name}}</div>
          </div>
          <div class="row">
            <div class="col-md-3">City:</div>
            <div class="col-md-6">{{employee.cityname}}</div>
          </div>
          <div class="row">
            <div class="col-md-3">Address:</div>
            <div class="col-md-6">{{employee.address}}</div>
          </div>
          <div class="row">
            <div class="col-md-3">Company:</div>
            <div class="col-md-6">{{employee.company}}</div>
          </div>
          <div class="row">
            <div class="col-md-3">Designation:</div>
            <div class="col-md-6">{{employee.designation}}</div>
          </div>
        </div>
      </div>
      <div class="row mt-4">
        <div class="col-md-4">
          <button class="btn btn-outline-secondary mr-3"
                  style="width:80px;margin-right:10px;"
                  (click)="onBack()">
            <i class="fa fa-chevron-left"></i> Back
          </button>
          <button class="btn btn-outline-primary"
                  style="width:80px;margin-right:10px;"
                  [routerLink]="['/employees', employee.id,'edit']">
            Edit
          </button>
        </div>
      </div>
    </div>
    <div class="alert alert-danger"
         *ngIf="errorMessage">
      {{errorMessage}}
    </div>
  </div>


Create the navigation menu component now.  

ng g component NavMenu  

Modify the class file with the code below.  

nav-menu.component.ts
import { Component, OnInit } from '@angular/core';

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

  isExpanded = false;

  ngOnInit() {
  }

  collapse() {
    this.isExpanded = false;
  }

  toggle() {
    this.isExpanded = !this.isExpanded;
  }

}


Change the template file with the code below.  

nav-menu.component.html
<header>
    <nav class='navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3'>
      <div class="container">
        <a class="navbar-brand" [routerLink]='["/"]'>Employee App</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse"
          aria-label="Toggle navigation" [attr.aria-expanded]="isExpanded" (click)="toggle()">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse" [ngClass]='{"show": isExpanded}'>
          <ul class="navbar-nav flex-grow">
            <li class="nav-item" [routerLinkActive]='["link-active"]' [routerLinkActiveOptions]='{ exact: true }'>
              <a class="nav-link text-dark" [routerLink]='["/"]'>Home</a>
            </li>
            <li class="nav-item" [routerLinkActive]='["link-active"]'>
              <a class="nav-link text-dark" [routerLink]='["/employees"]'>Employees</a>
            </li>
          </ul>
        </div>
      </div>
    </nav>
  </header>
  <footer>
    <nav class="navbar navbar-light bg-white mt-5 fixed-bottom">
      <div class="navbar-expand m-auto navbar-text">
        Developed with <i class="fa fa-heart"></i> by <b>Sarathlal
          Saseendran</b>
      </div>
    </nav>
  </footer>


We can also change the stylesheet file with the code below.  

nav-menu.component.css
html {
    font-size: 14px;
}

@media (min-width: 768px) {
    html {
        font-size: 16px;
    }
}

.fa-heart {
    color: hotpink;
}

Create the final component Home now.  

ng g component home  

There is no code change for the class file. We can change the html template file with the code below.  

home.component.html

<div style="text-align:center;">
    <h3>Easily use MockAPI.io with Angular 14</h3>
    <p>Welcome to our new single-page Employee application using MockAPI</p>
    <img src="../../assets/angular mockapi.jpg" width="800px">
</div>

We must add below route values in the app-routing.module class as well.  

app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmployeeDetailComponent } from './employee/employee-detail/employee-detail.component';
import { EmployeeEditComponent } from './employee/employee-edit/employee-edit.component';
import { EmployeeListComponent } from './employee/employee-list/employee-list.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' },
  {
    path: 'employees',
    component: EmployeeListComponent
  },
  {
    path: 'employees/:id',
    component: EmployeeDetailComponent
  },
  {
    path: 'employees/:id/edit',
    component: EmployeeEditComponent
  },
]

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


Change the AppComponent with the code below.

app.component.ts
import { AfterContentChecked, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { LoaderService } from './loader.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterContentChecked {
  title = 'Angular14MockAPI';
  showLoader!: boolean;
  constructor(private loader: LoaderService, private ref: ChangeDetectorRef) {

  }
  ngOnInit() {
    this.loader.controlLoader.subscribe((result) => {
      this.showLoader = result;
    });
  }

  ngAfterContentChecked() {
    this.ref.detectChanges();
  }
}

We can change the app.component.html with the code below.  

app.component.html
<body>
  <app-nav-menu></app-nav-menu>
  <div class="container">
    <div class="file-loader" *ngIf="showLoader">
      <div class="upload-loader">
        <div class="loader"></div>
      </div>
    </div>
    <router-outlet></router-outlet>
  </div>
</body>

Change the stylesheet with the code below.

app.component.css
/* Spin Start*/

.file-loader {
    background-color:
  rgba(0, 0, 0, .5);
    overflow: hidden;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100000 !important;
  }

  .upload-loader {
    position: absolute;
    width: 60px;
    height: 60px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }

    .upload-loader .loader {
      border: 5px solid
  #f3f3f3 !important;
      border-radius: 50%;
      border-top: 5px solid
  #005eb8 !important;
      width: 100% !important;
      height: 100% !important;
      -webkit-animation: spin 2s linear infinite;
      animation: spin 2s linear infinite;
    }

  @-webkit-keyframes spin {
    0% {
      -webkit-transform: rotate(0deg);
    }

    100% {
      -webkit-transform: rotate(360deg);
    }
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  /* Spin End*/


We have completed the entire coding part. We can run the application now.

Click the Employees menu and add a new employee record.

Added employees will be listed as a grid format on the screen.

We have search, edit, and remove features also available in the application.  

Conclusion
In this post, we have seen how to create a mock API using MockAPI.io. MockAPI provides a free plan to create one project and four resources. We have created an employee resource and consumed this resource from an Angular 14 application. We have seen all CRUD operations using MockAPI and Angular 14 application. MockAPI also provides various paid plans as well. You can try from your end and feel free to write your valuable feedback.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in