Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE :: How To Use HTTP Interceptor In Angular?

clock November 28, 2022 07:16 by author Peter

Angular Interceptor helps us modify the HTTP request by intercepting it before the request is sent to the backend. You can also change the incoming response from the backend. The Interceptor globally captures all incoming and outgoing requests in one place. We can use it to add custom headers to the outgoing request, log the incoming response, etc.

 


What is HTTP Interceptor?
An Angular HTTP interceptor sits between your application and the backend. When the application makes a request, the interceptor sees the request (HttpRequest) before sending it to the backend. You can access the request headers and body by intercepting the request. This allows us to transform the request before sending it to the server.


When the response (HttpResponse) arrives from the backend, interceptors can transform it before forwarding it to the application. One of the main advantages of HTTP interceptors is the ability to add an Authorization header to every request. You can do this manually, but it's tedious and error-prone. Another benefit is the ability to catch and log errors generated by requests.

How to Create Interceptor?
To implement an interceptor, we need to create an injectable service that implements the HttpInterceptor interface.
@Injectable() export class MyHttpInterceptor implements HttpInterceptor {

This class should implement the Intercept method
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //Do the code whatever you want with the HTTP request

    return next.handle(req);
}


This class is exposed in the root module using the HTTP_INTERCEPTORS injection token.
providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: MyHttpInterceptor,
        multi: true
    }
],


Interface: HTTP Interceptor
At the guts of the Interceptor, logic is the HttpInterceptor Interface. we have a tendency to should Implement it in our Interceptor Service.

The interface contains one method Intercept with the subsequent signature
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>

HTTP Request
The first argument is HttpRequest.

HttpRequest is an intercepted outgoing HTTP request. It integrates URLs, methods, headers, body, and various request configurations.

HttpRequest is an immutable class. In any way, we cannot accommodate genuine claims. To make adjustments, we want to duplicate the original request using the HttpRequest.clone

HTTP Handler

The second argument is httpHandler

HttpHandler sends the HttpRequest to the next Controller using the HttpHandler.handleMethod. The next handler can be another interceptor in on Thread or the Http Backend.

Let's see the example

Create MyHttpInterceptor.ts under /app folder and paste the below code
import {Injectable} from "@angular/core";
import {HttpEvent, HttpHandler, HttpInterceptor,HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs/Observable";

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
    constructor() {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req);
    }
}

In the body of the method, you should be able to modify the HttpRequest object. Once done, you can select the HttpHandler.handle method from the HttpHandler with the HttpRequest object. The HttpHandler.handle method calls the fighter thus or sends a request to the main server.

App.Module
Whole code from the app module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http';
import { FormsModule } from '@angular/forms';

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

import { GitHubService } from './github.service';
import {MyHttpInterceptor} from './MyHttpInterceptor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [GitHubService,
    {
    provide: HTTP_INTERCEPTORS,
    useClass: MyHttpInterceptor,
    multi: true
  }
],
  bootstrap: [AppComponent]
})
export class AppModule { }


If you have faced any error regarding the import module please check your package.json file and install the required package if not installed.
So, here interceptor-adding process is done let's run the app and you can see every HTTP calls interceptor, You can put the debugger in the interceptor and see.
Let's add content type using interceptor

Content Type Adding
To modify the request we want to clone it using HttpRequest.clone
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });

The header object is also unchanged. Therefore, we need to duplicate it using the headers.set method. The header.set method copies the current header and adds/modifies the new header value and returns the copied header.

We can also use the header.append. The append technique continually appends the header albeit the worth is already present.

And we can also remove the header like the one below shown
req = req.clone({ headers: req.headers.delete('Content-Type','application/json') });

If you want to add authorization token then we can add a token as shown below
const bearerToken: string =authService.Token; // here you can use your service method where get token
if (token) {
    req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + bearerToken) });
}


So we can change or add code as per our requirement like adding logging, modifying response, catching the errors, etc...



AngularJS Hosting Europe - HostForLIFE :: Angular CLI MODULE_NOT_FOUND Error

clock November 17, 2022 09:45 by author Peter

When we sometimes create a new project but can't create the project because of an error like the one below.

Here I have provided steps to resolve the issue.

Step 1
Run CMD as Run as administrator mode.

Step 2
Uninstall angular cli.
npm uninstall -g @angular/cli

Step 3
Remove npm package files from the appdata folder.

Step 4
Open Run option by pressing Windows + R key. Then type %appdata% and press OK.

Step 5
Open the npm folder from the Roaming folder that you got in explorer.

Step 6
Delete ng and ng.cmd files from the npm folder if exists.
Open node_modules folder from there and delete @angular and angular/cli folder if exists.

Step 7
Reinstall the angular cli
npm install -g @angular/cli

Create a new Project with the use of command

App is created and run with ng serve command like this



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



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.



AngularJS Hosting Europe - HostForLIFE :: How To Create Voice Recognition Using Ngx-Speech-Recognition In Angular?

clock September 16, 2022 06:52 by author Peter

In this article, we are going to see how voice recognition can translate spoken words into text using closed captions to enable a person with hearing loss to understand what others are saying. It's most useful for students, employees, and client communications purposes rather than using voice commands instead of typing.

First, we have created a basic Angular application using Angular CLI.

Here I have used ngx Speech Recognition for custom plugins or we can create a separate library inside the application, and be able to use the newly created library.  

Please refer to this link for angular custom library creations.

I have used Ngx Speech Recognition service library from the applications created as ngx-speech-recognition-test.

How to Create Voice Recognition using Ngx-Speech-Recognition in Angular

Then created main and sub-components. The main components are just using some project-related purpose or whatever content we need to add this main component. If you don’t need it, please ignore it. In the sub-components, we used the voice recognition part. Please check the following code.

Here I have added all sub-components codes.

Sub.component.ts

import {
    Component
} from '@angular/core';
import {
    ColorGrammar
} from './sub.component.grammar';
import {
    SpeechRecognitionLang,
    SpeechRecognitionMaxAlternatives,
    SpeechRecognitionGrammars,
    SpeechRecognitionService,
} from '../../../../../projects/ngx-speech-recognition-test/src/public_api';
@Component({
    selector: 'test-sub',
    templateUrl: './sub.component.html',
    styleUrls: ['./sub.component.css'],
    providers: [
        // Dependency Inject to SpeechRecognitionService
        // like this.
        {
            provide: SpeechRecognitionLang,
            useValue: 'en-US',
        }, {
            provide: SpeechRecognitionMaxAlternatives,
            useValue: 1,
        }, {
            provide: SpeechRecognitionGrammars,
            useValue: ColorGrammar,
        },
        SpeechRecognitionService,
    ],
})
export class SubComponent {
    public started = false;
    public message = '';
    constructor(private service: SpeechRecognitionService) {
        // Dependency The injected services are displayed on the console.
        // Dependence was resolved from SubComponent's provider.
        this.service.onstart = (e) => {
            console.log('voice start');
        };
        this.service.onresult = (e) => {
            this.message = e.results[0].item(0).transcript;
            console.log('voice message result', this.message, e);
        };
    }
    start() {
        this.started = true;
        this.service.start();
    }
    stop() {
        this.started = false;
        this.service.stop();
    }
}


SpeechRecognitionLang, SpeechRecognitionMaxAlternatives, SpeechRecognitionGrammars and SpeechRecognitionService all imported from ngx-speech-recognition-test.

We need to inject SpeechRecognitionServices. SpeechRecognitionLang provides mapping, we can map language code mentioned 'en-US'

SpeechRecognitionMaxAlternatives is Recognition voice count. I have marked 1.  

SpeechRecognitionGrammars purpose checked to translate text for grammar validations.  

ColorGrammar(Sub.component.grammar.ts). All the setup configurations are in the above codes.

Sub.component.grammar.ts
Sub.component.grammar.ts
/**
 * @see https://developer.mozilla.org/ja/docs/Web/API/SpeechGrammarList#Examples
 */
export const ColorGrammar = new SpeechGrammarList();
ColorGrammar.addFromString(`#JSGF V1.0;
grammar colors;
public <color> = aqua | azure | beige | bisque |
  black | blue | brown | chocolate | coral | crimson | cyan | fuchsia |
  ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki |
  lavender | lime | linen | magenta | maroon | moccasin | navy | olive |
  orange | orchid | peru | pink | plum | purple | red | salmon | sienna |
  silver | snow | tan | teal | thistle | tomato | turquoise |
  violet | white | yellow ;
`, 1);

Sub.component.html
<p>Voice message: {{message}}</p>
    <button [disabled]="started" (click)="start()">Voice start</button>
    <button [disabled]="!started" (click)="stop()">Voice end</button>
<p>lang: en-US</p>


Sub.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SubComponent} from './components';
@NgModule({
  imports: [CommonModule],
  declarations: [SubComponent],
  exports: [SubComponent,],
})
export class SubModule { }


Then copy and paste the codes to demo.component.ts, demo. Component.html and demo.module.ts.

demo.component.ts
import { Component } from '@angular/core';
@Component({
  selector: 'demo-root',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.css'],
})
export class DemoComponent { }


demo.component.html
<test-main></test-main>
<test-sub></test-sub>


Demo.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { DemoComponent } from './demo.component';
import { MainComponent } from './components';
import { SubModule } from '../demo/sub';
import { SpeechRecognitionModule } from '../../projects/ngx-speech-recognition-test/src/public_api';
@NgModule({
  declarations: [
    // app container.
    DemoComponent, MainComponent,
  ],
  imports: [
    BrowserModule,
    CommonModule,
    RouterModule,
    SpeechRecognitionModule.withConfig({
      lang: 'en',
      interimResults: true,
      maxAlternatives: 10,
      // sample handlers.
  onaudiostart:  (ev: Event) => console.log('onaudiostart',ev),
      onsoundstart:  (ev: Event) => console.log('onsoundstart',ev),
      onspeechstart: (ev: Event) => console.log('onspeechstart',ev),
      onspeechend:   (ev: Event) => console.log('onspeechend',ev),
      onsoundend:    (ev: Event) => console.log('onsoundend',ev),
      onaudioend:    (ev: Event) => console.log('onaudioend', ev),
      onresult:      (ev: SpeechRecognitionEvent) => console.log('onresult',ev),
      onnomatch:     (ev: SpeechRecognitionEvent) => console.log('onnomatch',ev),
      onerror:       (ev: SpeechRecognitionError) => console.log('onerror',ev),
      onstart:       (ev: Event) => console.log('onstart', ev),
      onend:         (ev: Event) => console.log('onend',ev),
    }),
    // In SubModule, Component's providers are doing Demo
    // using SpeechRecognitionService generated.
    //
    SubModule,
  ],
  providers: [],
  bootstrap: [DemoComponent]
})
export class DemoModule { }

Added the above codes in the applications. Then please run the applications using ng serve --open or npm start. The application windows http://localhost:4200/ will be opened in the default browser.

If going to run the application first time and click the voice start button browser asks “Use your microphone” permission. If click allows and continues the following steps.

 

After that, I have to click the Voice start button and then speak input words like “hello welcome to angular”. The voice recognition captures them one by one and stores them into the message. Then, give another input into the voice like “I learn typescript”. And click the Voice end button. The whole words into the single lines of message like “hello welcome to angular I learn typescript”.

If you click the voice end button and we have end voice input process has complete sentence will show in the message field. I hope this article is of most helpful for you.



AngularJS Hosting Europe - HostForLIFE :: Building Blocks Of Angular

clock September 8, 2022 10:05 by author Peter

In this article, we are going to see about the building blocks of Angular
    Modules
    Components
    Templates
    Metadata
    Data binding
    Directives
    Services
    Dependency injection

Modules
In angular app has at least one module which we call app module. A module is a container for a group of related components. There are two types of modules one is encapsulating block of function within the single component and the other is encapsulating block of function within a single or group of components by providing exposure in an interface. we need to divide our app module into sub smaller modules and each module is responsible for a specific section.

Components
Its component represents a unique "View" and "View Model" in Model-View-ViewModel (MVVM) pattern or exactly like what components do in Angular. The "View" or Template shows how the complete component will look–when displayed on the browser. "View Model" has all required logic parts to provide "View" with rich functionality and data.

In this case, we followed some steps like below
    Create the Component.
    Register the component in module.
    Add the element in HTML Markup.

Create the Component.

To create the component, we can use the below ng command followed by some name.  
ng generates component component_name

OR

ng g c component_name

Here I have entered the command like ng g c sample. After successfully create component, it will create additionally  
    sample.component.ts (Class with @Component decorator)
    sample.component.html (For the template design)
    sample.component.css (For stylesheets)

Register the component in module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { SampleComponent } from './sample.component';
@NgModule({
  declarations: [AppComponent,SampleComponent],
  imports: [ BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


I have registered the component on the appmodule.ts page. We are going to declarations in the samplecomponent.

Add the element in HTML Markup.

Added some markup design in the sample.component.html page like the below code.
<h3>Test Component</h3>

Templates
The templates' view represents a view that improves HTML with Angular functionality like data binding.
import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    template: '<h2>Test Angular</h2>'
})
export class AppComponent {}


If we want is to encapsulate the data in the container and show it in the template markup dynamically.

In the template to encapsulate the data and when the data changes here at runtime, Angular automatically updates it in the browser view as well.
import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    template: '<h2> {{ name + "Angular" }}</h2>'
})
export class AppComponent {name = "Test Sat";}


Metadata

Metadata helps in connecting everything in the applications, a "View" with a "View Model" with styles.

    the selector is Metadata in Angular the custom HTML to be included with the component.
    template URL is the exclusive URL for the template to be used when processing the component,
    an array of directives with this kind of Metadata will tell Angular which other Component or the directives should be included in that component.
    an array of style URLs with this type of Metadata you can easily define customized styles for the component.
    Angular how to inject dependencies like services in a component or @RouterConfig that helps you to configure routing in your project application.

Data binding
Data binding is a technique, where the data stays in sync between the component and the view.

There are two different types of data bindings
    one-way  
    two-way binding.

One-way data binding

One-way data binding is a one-way interaction between a component and its HTML template. If you perform any changes in your component, then it will reflect the HTML elements also.
import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    template: '<h2> {{  name }}</h2>'
})
export class AppComponent {name = "Test Sat";}

Two-way data binding
Two-way data binding is a both-way interaction with components and HTML, data flows in both ways from component to HTML views and HTML views to the component. A simple example is ngModel. If you do any changes in your object model then, it reflects in your HTML view.

Here testdata is one of the objects and another one temptestdata. Initially assign some values in the testdata object and change the value after the user manually enter using passdata click event.
import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
     styleUrls: ['./app.component.css']
})
export class AppComponent {
  testdata:string = "Virat Sat";
  temptestdata:String="";
passData(){
    this.temptestdata=testdata;
  }
}


HTML
<input type="text" (ngModel)="testdata">
<button (ngClick)="passData()"> Pass Data Click here </button>
<h3>{{temptestdata}}</h3>


There are three types of Directives present in Angular

Components Directive The component can be used as a directive. Every component has an and Output option to pass between the component and its parent HTML elements.

<selector-name [input-reference]="input-value"> </selector-name>
For Example,
<list-data [items]="datavalues"></list-data>

Structural Directive is like *ngFor and *ngIf which enables you to make changes to DOM with the help of adding or by the Input moving nodes.
<div *ngIf="true">Test Sat data</div>
<li *ngFor="let data of list-data">
  {{ data }}
</li>


Attribute Directive helps in adding behavior or do a change in the look or appearance of a specific element just like ngmodel directive which implements two-way data binding is an Attribute Directive.
<HTMLTag [attrDirective]='value' /></HTMLTag>
For Example,
<p [showToolTip]='Test Virat' />


Services
Services simply help in making reuse of service. As the project becomes bigger naturally more components will add to it and which also will require data to access. So, every time making a copy-paste of code it will create a single reusable singleton data service.

Dependency injection
Dependency Injection to inject the necessary dependencies for a given component/service at runtime and provide flexibility, extensibility, and testability to the framework and your application.

import { Component } from '@angular/core';
import { Service } from './service';
@Component({
    selector: 'app-root',
    template: `
    <ul>
        <li *ngFor="let data of datalist">
            {{ data }}
        </li>
    </ul>
})
export class AppComponent {
    datalist;
    constructor(){
        let service = new Service();
        this.datalist = service.getCourses();
    }
}

We need to explicitly instruct the Angular to create an instance of Service and passes to our AppComponent. This concept is called Dependency Injection. So, we should instruct Angular to inject the dependency of this component into its constructor.

I hope this article was most helpful for you.



AngularJS Hosting Europe - HostForLIFE :: How To Use Kendo UI In Angular Application?

clock September 1, 2022 07:26 by author Peter

Preconditions
    Basic knowledge of Angular CLI
    Bootstrap
    Node.js
    V.S. Code

We Covers the belowing things
    Create Angular application
    Create header,side menu and layout component with admin module.
    Angular Routing
    Kendo UI setup

Now let's use following command to create angular project,
ng new KendoUI
cd KendoUI

Now install bootstrap by using the following command,
npm install bootstrap --save

Now install KendoUI packages using following command,
npm install --save @progress/kendo-angular-charts @progress/kendo-angular-common @progress/kendo-angular-intl @progress/kendo-angular-l10n @progress/kendo-angular-popup @progress/kendo-drawing hammerjs @progress/kendo-licensing

Now install KendoUI theme using following command, I used default theme,
Default theme
npm install --save @progress/kendo-theme-default


Bootstrap theme
npm install --save @progress/kendo-theme-bootstrap

Material theme
npm install --save @progress/kendo-theme-material

Now Create the dashboard and layout component using the following command,
ng g c dashboard
ng g c layout

Now add the code in the following pages-:
Add this in app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { GridModule } from '@progress/kendo-angular-grid';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { LayoutComponent } from './layout/layout.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { LabelModule } from '@progress/kendo-angular-label';
import { ChartsModule } from '@progress/kendo-angular-charts';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { DialogModule } from '@progress/kendo-angular-dialog';
import { UploadModule } from '@progress/kendo-angular-upload';
import { FileSelectModule } from '@progress/kendo-angular-upload';
import { PDFExportModule } from '@progress/kendo-angular-pdf-export';
import { NotificationModule } from '@progress/kendo-angular-notification';
import { NavigationModule } from '@progress/kendo-angular-navigation';
import { IconsModule } from '@progress/kendo-angular-icons';
import { IndicatorsModule } from '@progress/kendo-angular-indicators';
import { LayoutModule } from '@progress/kendo-angular-layout';

@NgModule({
  declarations: [
    AppComponent,
    LayoutComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    GridModule,
    BrowserAnimationsModule,
    InputsModule,
    LabelModule,
    ChartsModule,
    ButtonsModule,
    DialogModule,
    UploadModule,
    FileSelectModule,
    PDFExportModule,
    NotificationModule,
    NavigationModule,
    IconsModule,
    IndicatorsModule,
    LayoutModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Add this in app.component.html
<router-outlet></router-outlet>

Add this in app-routing.module.ts
import {
    NgModule
} from '@angular/core';
import {
    RouterModule,
    Routes
} from '@angular/router';
import {
    DashboardComponent
} from './dashboard/dashboard.component';
import {
    LayoutComponent
} from './layout/layout.component';
const routes: Routes = [{
    path: 'Admin',
    component: LayoutComponent,
    children: [{
        path: 'Dashboard',
        component: DashboardComponent
    }]
}, {
    path: '**',
    redirectTo: "/Admin/Dashboard",
    pathMatch: 'full'
}, {
    path: '',
    redirectTo: "/Admin/Dashboard",
    pathMatch: 'full'
}];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}


Add this in layout.component.ts
import {
    Component,
    OnInit
} from '@angular/core';
@Component({
    selector: 'app-layout',
    templateUrl: './layout.component.html',
    styleUrls: ['./layout.component.css']
})
export class LayoutComponent implements OnInit {
    private data: any;
    public kendokaAvatar = '/assets/img/0.jpg';
    public logout = '/assets/img/logout.png';
    constructor() {}
    ngOnInit(): void {}
    public bottomNavigationItems: Array < any > = [{
        text: 'Home',
        icon: 'home',
        selected: true
    }, {
        text: 'Calendar',
        icon: 'calendar'
    }, {
        text: 'Notifications',
        icon: 'bell'
    }];
}


Add this in layout.component.html
<!--The content below is only a placeholder and can be replaced.-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Kendo</title>
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<!-- <kendo-breadcrumb [items]="breadCrumbItems"></kendo-breadcrumb> -->
<!-- <kendo-bottomnavigation [border]="true" [items]="bottomNavigationItems"></kendo-bottomnavigation> -->
<br />
  <div id="wrapper">
    <!-- Navigation -->
    <nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
      <!-- <div class="navbar-header"> -->
        <!-- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button> -->
        <!-- <a class="navbar-brand" href="index.html">Kendo Project</a> -->
      <!-- </div> -->
      <!-- /.navbar-header -->
      <!-- /.navbar-top-links -->
      <kendo-appbar position="top">
        <!-- <kendo-appbar-section>
            <button class="k-button k-button-clear">
                <kendo-icon name="menu"></kendo-icon>
            </button>
        </kendo-appbar-section> -->
        <!-- <kendo-appbar-section>
            <h1 class="title">Kendo Project</h1>
        </kendo-appbar-section> -->
        <kendo-appbar-spacer width="32px"></kendo-appbar-spacer>
        <kendo-appbar-section>
            <ul>
                <li><a class="DashFont" [routerLink]="['/Admin/Dashboard']">Dashboard</a></li>
                <!-- <li><a [routerLink]="['/Admin/userlist']">Users</a></li>
                <li><a [routerLink]="['/Admin/profile']">Profile</a></li>
                <li><a [routerLink]="['/Admin/userserver']">User List</a></li> -->
            </ul>
        </kendo-appbar-section>
        <kendo-appbar-spacer></kendo-appbar-spacer>
        <kendo-appbar-section>
          <a [routerLink]="['/Admin/profile']"><kendo-avatar [imageSrc]="kendokaAvatar" shape="circle" width="26px" height="26px"> </kendo-avatar></a>
        </kendo-appbar-section>
        <kendo-appbar-section class="actions">
          <a [routerLink]="['/AdminLogout']"><kendo-avatar [imageSrc]="logout" shape="circle" width="26px" height="26px"> </kendo-avatar></a>
            <kendo-badge-container>
                <button class="k-button k-button-clear">
                    <kendo-icon name="bell"></kendo-icon>
                </button>
                <kendo-badge shape="dot" themeColor="warning" size="small" position="inside"></kendo-badge>
            </kendo-badge-container>
            <span class="k-appbar-separator"></span>
        </kendo-appbar-section>
    </kendo-appbar>
      <!-- <div class="navbar-default sidebar" role="navigation">
        <div class="sidebar-nav navbar-collapse">
          <ul class="nav" id="side-menu">

            <li>
              <a [routerLink]="['/Admin/Dashboard']"><i class="fa fa-edit fa-fw"></i>Dashboard</a>
            </li>
            <li>
              <a [routerLink]="['/Admin/userlist']"><i class="fa fa-edit fa-fw"></i>Users List</a>
            </li>
            <li>
              <a [routerLink]="['/Admin/userserver']"><i class="fa fa-edit fa-fw"></i>Users Server List</a>
            </li>
            <li>
              <a [routerLink]="['/Admin/imagegrid']"><i class="fa fa-edit fa-fw"></i>Image Grid</a>
            </li>
            <li>
              <a [routerLink]="['/AdminLogout']"><i class="fa fa-edit fa-fw"></i>Logout</a>
            </li>
          </ul>
        </div>
      </div> -->
    </nav>
    <div id="page-wrapper">
      <div class="row">
        <div class="col-lg-12">
         <router-outlet></router-outlet>
        </div>
        <!-- /.col-lg-12 -->
      </div>
      <!-- /.row -->
    </div>
  </div>
  <!-- /#page-wrapper -->
  <!-- /#wrapper -->
</body>
</html>

Add this inlayout.component.css
: host {
    padding: 0;
}
kendo - appbar.title {
    font - size: 18 px;
    margin: 10 px;
}
kendo - badge - container {
    margin - right: 8 px;
}
kendo - appbar ul {
    font - size: 14 px;
    list - style - type: none;
    padding: 0;
    margin: 0;
    display: flex;
}
kendo - appbar li {
    margin: 0 9 px;
}
kendo - appbar li: hover {
    cursor: pointer;
    color: #d6002f;
}
kendo - appbar.actions.k - button {
    padding: 0;
}
kendo - breadcrumb {
    margin - left: 30 px;
}.DashFont {
    font - size: 16 px;
    font - family: 'Segoe UI', Tahoma, Geneva, Verdana, sans - serif;
}

Add this in dashboard.component.ts
import {
    Component,
    OnInit
} from '@angular/core';
@Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
    ngOnInit(): void {}
    constructor() {}
    public events: string[] = [];
    public series: any[] = [{
        name: "India",
        data: [
            3.907, 7.943, 7.848, 9.284, 9.263, 9.801, 3.89, 8.238, 9.552, 6.855,
        ],
    }, {
        name: "Russian Federation",
        data: [4.743, 7.295, 7.175, 6.376, 8.153, 8.535, 5.247, -7.832, 4.3, 4.3],
    }, {
        name: "Germany",
        data: [
            0.01, -0.375, 1.161, 0.684, 3.7, 3.269, 1.083, -5.127, 3.69, 2.995,
        ],
    }, {
        name: "World",
        data: [
            1.988, 2.733, 3.994, 3.464, 4.001, 3.939, 1.333, -2.245, 4.339, 2.727,
        ],
    }, ];
    public categories: number[] = [
        2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
    ];
    public onRender(): void {
        this.log("render");
    }
    public onAxisLabelClick(e: any): void {
        this.log("axisLabelClick", e);
    }
    public onLegendItemClick(e: any): void {
        this.log("legendItemClick", e);
    }
    public onLegendItemHover(e: any): void {
        this.log("legendItemHover", e);
    }
    public onPlotAreaClick(e: any): void {
        this.log("plotAreaClick", e);
    }
    public onPlotAreaHover(e: any): void {
        this.log("plotAreaHover", e);
    }
    public onSeriesClick(e: any): void {
        this.log("seriesClick", e);
    }
    public onSeriesHover(e: any): void {
        this.log("seriesHover", e);
    }
    private log(event: string, arg: any = null): void {
        this.events.push(`${event}`);
        console.log(arg);
    }
    public data: any[] = [{
        kind: 'Hydroelectric',
        share: 0.175
    }, {
        kind: 'Nuclear',
        share: 0.238
    }, {
        kind: 'Coal',
        share: 0.118
    }, {
        kind: 'Solar',
        share: 0.052
    }, {
        kind: 'Wind',
        share: 0.225
    }, {
        kind: 'Other',
        share: 0.192
    }];
    public labelContent(e: any): string {
        return e.category;
    }
}


Add this in dashboard.component.html
<kendo-chart>
    <kendo-chart-title text="Units sold"></kendo-chart-title>
    <kendo-chart-category-axis>
        <kendo-chart-category-axis-item
            [categories]="['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'august' , 'september' , 'October', 'november', 'December']"
            [title]="{ text: 'Months' }">
        </kendo-chart-category-axis-item>
    </kendo-chart-category-axis>
    <kendo-chart-series-defaults [highlight]="{ inactiveOpacity: 0.3 }">
    </kendo-chart-series-defaults>
    <kendo-chart-series>
      <kendo-chart-series-item type="area" [data]="[123, 276, 310, 212, 240, 156, 98, 210, 200, 220, 180, 170]">
      </kendo-chart-series-item>
      <kendo-chart-series-item type="area" [data]="[165, 210, 287, 144, 190, 167, 212, 190, 210, 250, 260, 220]">
      </kendo-chart-series-item>
      <kendo-chart-series-item type="area" [data]="[56, 140, 195, 46, 123, 78, 95, 240, 250, 210, 280, 290, 320]">
      </kendo-chart-series-item>
    </kendo-chart-series>
  </kendo-chart>
<hr>
<kendo-chart>
    <kendo-chart-series>
      <kendo-chart-series-item
          type="donut" [data]="data"
          categoryField="kind" field="share">
        <kendo-chart-series-item-labels
          [content]="labelContent"
          color="#fff" background="none">
        </kendo-chart-series-item-labels>
      </kendo-chart-series-item>
    </kendo-chart-series>
    <kendo-chart-legend [visible]="false"></kendo-chart-legend>
  </kendo-chart>

JavaScript

Add this in package.json dependencies

"private": true,
  "dependencies": {
    "@angular/animations": "~12.1.0-",
    "@angular/common": "~12.1.0-",
    "@angular/compiler": "~12.1.0-",
    "@angular/core": "~12.1.0-",
    "@angular/forms": "~12.1.0-",
    "@angular/localize": "~12.1.0-",
    "@angular/platform-browser": "~12.1.0-",
    "@angular/platform-browser-dynamic": "~12.1.0-",
    "@angular/router": "~12.1.0-",
    "@progress/kendo-angular-buttons": "^7.0.0",
    "@progress/kendo-angular-charts": "^6.0.0",
    "@progress/kendo-angular-common": "^2.0.0",
    "@progress/kendo-angular-dateinputs": "^6.0.0",
    "@progress/kendo-angular-dialog": "^6.0.1",
    "@progress/kendo-angular-dropdowns": "^6.0.0",
    "@progress/kendo-angular-excel-export": "^4.0.0",
    "@progress/kendo-angular-grid": "^6.0.1",
    "@progress/kendo-angular-icons": "^1.0.0",
    "@progress/kendo-angular-indicators": "^1.1.2",
    "@progress/kendo-angular-inputs": "^8.0.0",
    "@progress/kendo-angular-intl": "^3.0.0",
    "@progress/kendo-angular-l10n": "^3.0.0",
    "@progress/kendo-angular-label": "^3.0.0",
    "@progress/kendo-angular-layout": "^6.5.0",
    "@progress/kendo-angular-navigation": "^1.1.4",
    "@progress/kendo-angular-notification": "^3.0.4",
    "@progress/kendo-angular-pdf-export": "^3.0.0",
    "@progress/kendo-angular-popup": "^4.0.3",
    "@progress/kendo-angular-progressbar": "^2.0.3",
    "@progress/kendo-angular-treeview": "^6.0.0",
    "@progress/kendo-angular-upload": "^8.0.0",
    "@progress/kendo-data-query": "^1.0.0",
    "@progress/kendo-drawing": "^1.0.0",
    "@progress/kendo-licensing": "^1.0.2",
    "@progress/kendo-svg-icons": "^0.1.2",
    "@progress/kendo-theme-default": "^5.0.0",
    "rxjs": "~6.6.0",
    "tslib": "^2.2.0",
    "zone.js": "~0.11.4"
  },

Now add the attached images

Now run the following command.
npm i

Now, please run the application using the 'npm start' command and check the result.



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