Full Trust European Hosting

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

Node.js Hosting - HostForLIFE :: Building a Simple REST API in Node.js (GET, POST, PUT, DELETE)

clock July 10, 2025 08:19 by author Peter

Node.js is a robust framework for JavaScript server-side application development. GET, POST, PUT, and DELETE are the fundamental methods of every CRUD (Create, Read, Update, Delete) action, and we'll show you how to create a basic REST API that supports them in this article.

To keep things clear and easy, we'll use the well-liked Express framework.

First, start a Node.js project
To begin, make a new folder for your project and set up npm for it.

mkdir nodejs-api-demo
cd nodejs-api-demo
npm init -y


Then, install Express,
npm install express

Step 2. Create the API Server
Create a file named server.js and write the following code.
const express = require('express');
const app = express();
const port = 3000;

app.use(express.json()); // Middleware to parse JSON
let items = []; // Sample in-memory data store
// GET all items
app.get('/api/items', (req, res) => {
    res.json(items);
});
// POST a new item
app.post('/api/items', (req, res) => {
    const newItem = {
        id: Date.now(),
        name: req.body.name
    };
    items.push(newItem);
    res.status(201).json(newItem);
});

// PUT (update) an item by ID
app.put('/api/items/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const index = items.findIndex(item => item.id === id);

    if (index !== -1) {
        items[index].name = req.body.name;
        res.json(items[index]);
    } else {
        res.status(404).json({ message: 'Item not found' });
    }
});
// DELETE an item by ID
app.delete('/api/items/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const initialLength = items.length;
    items = items.filter(item => item.id !== id);

    if (items.length < initialLength) {
        res.json({ message: 'Item deleted' });
    } else {
        res.status(404).json({ message: 'Item not found' });
    }
});
// Hello World Endpoint
app.get('/', (req, res) => {
    res.send('Hello, World!');
});
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});


Step 3. Run Your API
Start your server using.

node server.js
Open your browser and go to:http://localhost:3000/ You should see "Hello, World!"

Use tools like Postman, Insomnia, or curl to test other endpoints:

  • GET http://localhost:3000/api/items
  • POST http://localhost:3000/api/items with JSON body: { "name": "Apple" }
  • PUT http://localhost:3000/api/items/123456789 with JSON: { "name": "Banana" }
  • DELETE http://localhost:3000/api/items/123456789

Summary
In this tutorial, you learned how to.

  • Initialize a Node.js project
  • Install and use Express.js
  • This setup is great for learning. For production, consider connecting to a real database, such as MongoDB, PostgreSQL, or MySQL.
  • Handle JSON data and HTTP methods (GET, POST, PUT, DELETE)
  • Build a basic in-memory CRUD API


Node.js Hosting - HostForLIFE :: Knowing Node.js's Event Loop, Callbacks, and Promises

clock July 3, 2025 08:00 by author Peter

The ability of Node.js to manage asynchronous processes is a major factor in its strength for creating quick, scalable network applications. You've probably heard of concepts like promises, callbacks, and event loops if you've ever dealt with Node.js.

In this post, we'll simplify these, go over actual code samples, and discuss how they all work together in the context of asynchronous programming.

Asynchronous programming: what is it?
JavaScript (as well as Node.js) only handles one instruction at a time since it is single-threaded. Unless we handle it asynchronously, if one operation (such as reading a file or sending a network request) takes a long time, it may prevent all other tasks from operating. Node.js can manage operations like file I/O, database queries, and API calls thanks to asynchronous programming, which keeps the application from stopping altogether.

The Event Loop: Node's Brain
The event loop is a mechanism in Node.js that allows it to perform non-blocking I/O operations. It listens for events and runs tasks from different queues (like timers or promise resolutions).

How does it work?

  • Executes synchronous code first.
  • Handles microtasks (like Promise.then()).
  • Then processes macrotasks (like setTimeout).
  • Repeats the cycle.

Example
console.log('Start');

setTimeout(() => {
  console.log('Timeout callback');
}, 0);

Promise.resolve().then(() => {
  console.log('Promise callback');
});
console.log('End');


Output
Start
End
Promise callback
Timeout callback


Why?

  • Promise.then() is a microtask, executed right after the synchronous code.
  • setTimeout() is a macrotask, executed after microtasks.

Callbacks: The Classic Asynchronous Tool
What is a Callback?

A callback is a function passed as an argument to another function. It’s executed when the first function completes - often asynchronously.
const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) {
    return console.error(err);
  }
  console.log(data);
});

Callback Hell
As you nest callbacks deeper, code can become hard to manage.
doTask1((res1) => {
  doTask2(res1, (res2) => {
    doTask3(res2, (res3) => {
      console.log(res3);
    });
  });
});


This “pyramid of doom” led to the evolution of promises.
Promises: A Modern Alternative

What is a Promise?
A promise is an object representing the eventual completion or failure of an asynchronous operation.
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Success!');
  }, 1000);
});
myPromise
  .then((value) => console.log(value))
  .catch((err) => console.error(err));

Promise States

  • Pending: Initial state.
  • Fulfilled: Operation completed successfully.
  • Rejected: Operation failed.

Promises in Action
function asyncTask() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve('Task Done'), 2000);
  });
}
asyncTask().then(console.log); // Outputs "Task Done" after 2 seconds


Async/Await: Cleaner Syntax with Promises

Introduced in ES2017, async/await allows you to write asynchronous code like it’s synchronous.
async function fetchData() {
  try {
    const data = await asyncTask();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
fetchData();

This is still based on promises, but it's easier to read and write.

Event Loop + Promises + Callbacks: Putting It Together

console.log('Start');

setTimeout(() => {
  console.log('setTimeout');
}, 0);

Promise.resolve().then(() => {
  console.log('Promise');
});

process.nextTick(() => {
  console.log('nextTick');
});
console.log('End');

Output
Start
End
nextTick
Promise
setTimeout

Execution order

  • Synchronous: Start, End
  • process.nextTick() (before promises)
  • Promises
  • Timers like setTimeout

Summary Table

Concept Purpose Queue
Event Loop Runs and manages all tasks          —
Callback Function called after async operation Callback queue
Promise Handles future values (success/failure) Microtask queue
setTimeout Delay execution of a task Macrotask queue
process.nextTick Runs after the current phase, before promises Microtask queue (special)

Conclusion

Node.js manages concurrency via non-blocking, asynchronous APIs and a clever event loop rather than threads. The event loop, promises, and callbacks are all crucial for creating Node.js applications with great performance. You will soon be able to create async code with confidence if you start small, try out samples, and gradually develop your mental model.



AngularJS Hosting Europe - HostForLIFE :: Key Features of Node.js: A Clear Explanation

clock July 1, 2025 07:24 by author Peter

An open-source, cross-platform runtime environment called Node.js enables server-side JavaScript execution. It is incredibly fast because it is based on Chrome's V8 engine. Node.js's non-blocking, event-driven architecture is one of its strongest features; it makes it easier to create high-performance applications. Because we can use the same language-JavaScript-for both front-end and back-end development, many Indian developers.

Why Node.js is So Popular: 7 Key Features Explained?
Speed, scalability, and performance are essential for creating contemporary web applications in the fast-paced digital world of today. Node.js excels in this situation. Node.js has grown to be one of the most popular platforms since its launch, used by both developers and businesses, ranging from startups to internet behemoths like Netflix, PayPal, and LinkedIn.

1. Single-Threaded but Super Efficient
Node.js operates on a single-threaded event loop, in contrast to conventional server models that employ many threads. This implies that thousands of requests can be handled concurrently without requiring the creation of a new thread for each one. I/O-intensive applications like as file upload systems, chat apps, and streaming services are best suited for this.

2. Asynchronous and Non-Blocking
In Node.js, operations like reading files or querying a database do not block the main thread. Instead, they run in the background and notify when the task is complete. This non-blocking nature allows other tasks to continue running smoothly, perfect for high-performance apps.

3. Event-Driven Architecture
Everything in Node.js revolves around events. Instead of waiting for a process to complete, Node.js listens for events and responds accordingly. This event-driven nature improves performance and helps build scalable applications.

4. Powered by Google’s V8 Engine
Node.js uses Google’s powerful V8 JavaScript engine, the same engine used in Chrome. It compiles JavaScript directly into machine code, making it extremely fast and efficient.

5. Cross-Platform Support

Whether you are using Windows, macOS, or Linux, Node.js works seamlessly across platforms. This makes development flexible and accessible to a wider range of developers.

6. NPM – Node Package Manager
With Node.js, you get access to NPM, the world’s largest software registry. It contains thousands of free packages and libraries that you can easily install and use in your projects, saving a lot of development time.

7. Built for Real-Time Applications

One of the biggest strengths of Node.js is its real-time capabilities. Whether you’re building a messaging app, online multiplayer game, or live tracking system, Node.js offers the perfect foundation for real-time communication.

Conclusion
Node.js is a comprehensive ecosystem that enables developers to create quick, scalable, and contemporary apps. It is not just another server-side technology. It is perfect for today's digital demands because of its single-threaded paradigm, asynchronous nature, and real-time characteristics. If you're an Indian developer who wants to improve your backend skills, learning Node.js can lead to a lot of options.



AngularJS Hosting Europe - HostForLIFE :: Use the ASP.NET Web API in Angular to Retrieve Data From a Database

clock June 25, 2025 09:45 by author Peter

In this article, I will explain how to call ASP.NET web API in your Angular project step by step. You need to enable CORS in your web API and fetch data from web API. It is easy to call API in Angular.


Step 1
Open SQL server of your choice and create a table and insert some records.

    CREATE TABLE [dbo].[Employee](  
        [Employee_Id] [int] IDENTITY(1,1) NOT NULL,  
        [First_Name] [nvarchar](50) NULL,  
        [Last_Name] [nvarchar](50) NULL,  
        [Salary] [money] NULL,  
        [Joing_Date] [nvarchar](50) NULL,  
        [Department] [nvarchar](50) NULL,  
     CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
    (  
        [Employee_Id] ASC  
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
    ) ON [PRIMARY]  
      
    GO  

Step 2

Open Visual Studio, click on New Project and create an empty web API application project.

After clicking on New Project, one window will appear. Select Web from the left panel, choose ASP.NET Web Application, give a meaningful name to your project, and then click on OK as shown in the below screenshot.

After clicking on OK one more window will appear; choose empty, check on empty Web API checkbox then click on OK as shown in the below screenshot

After clicking OK, the project will be created with the name of WebAPICRUD_Demo.

Step 3
Add Entity Framework now. For that, right click on Models folder, select Add, then select New Item, then click on it.

After clicking on a New item, you will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name MyModel (this name is not mandatory you can give any name) and click on Add.

After you click on "Add a window", the wizard will open, choose EF Designer from the database and click Next.

After clicking on Next a window will appear. Choose New Connection. Another window will appear, add your server name if it is local then enter a dot (.). Choose your database and click on OK.

The connection will be added. If you wish to save connect as you want. You can change the name of your connection below. It will save connection in web config then click on Next.

After clicking on NEXT another window will appear to choose database table name as shown in the below screenshot then click on Finish. Entity framework will be added and the respective class gets generated under the Models folder.

Following class will be added,
    namespace WebAPICURD_Demo.Models  
    {  
        using System;  
        using System.Collections.Generic;  
          
        public partial class Employee  
        {  
            public int Employee_Id { get; set; }  
            public string First_Name { get; set; }  
            public string Last_Name { get; set; }  
            public Nullable<decimal> Salary { get; set; }  
            public string Joing_Date { get; set; }  
            public string Department { get; set; }  
        }  
    }  

Step 4
Right click on Controllers folder, select Add, then choose Controller as shown in the below screenshot.


After clicking on the controller a window will appear to choose Web API 2 Controller-Empty, click on Add.


Fetch Data From Database Using ASP.NET Web API In Angular
After clicking on Add, another window will appear with DefaultController. Change the name to EmployeeController then click on Add. EmployeeController will be added under Controllers folder. Remember don’t change the Controller suffix for all controllers, change only highlight, and instead of Default just change Home as shown in the below screenshot.


Complete code for controller
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Net;  
    using System.Net.Http;  
    using System.Web.Http;  
    using WebAPICURD_Demo.Models;  
      
    namespace WebAPICURD_Demo.Controllers  
    {  
        public class EmployeeController : ApiController  
        {  
             
            private EmployeeEntities _db;  
            public EmployeeController()  
            {  
                _db =new EmployeeEntities();  
            }  
            public IEnumerable<Employee> GetEmployees()  
            {  
                return _db.Employees.ToList();  
            }  
        }  
    }  


Step 5
Now, enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command.
Install-Package Microsoft.AspNet.WebApi.Cors  

This command installs the latest package and updates all dependencies, including the core Web API libraries.

Step 6
Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.

Add namespace
using System.Web.Http.Cors;  

Add the following line of code,
    EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");  
    config.EnableCors(cors);  


Complete WebApiConfig.cs file code
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web.Http;  
    using System.Web.Http.Cors;  
      
    namespace WebAPICURD_Demo  
    {  
        public static class WebApiConfig  
        {  
            public static void Register(HttpConfiguration config)  
            {  
                // Web API configuration and services  
                  
                // Web API routes  
                config.MapHttpAttributeRoutes();  
      
                config.Routes.MapHttpRoute(  
                    name: "DefaultApi",  
                    routeTemplate: "api/{controller}/{id}",  
                    defaults: new { id = RouteParameter.Optional }  
                );  
      
                EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");  
                config.EnableCors(cors);  
            }  
        }  
    }  


Step 6
Open Visual Studio Code and create a new Angular project.
    ng new MyDemo  

Compile your project
    cd MyDemo  

Open your project in the browser,
    ng serve --open  

Step 7
Install bootstrap in your project and import in style.css file,
    npm install bootstrap –save  

    @import 'node_modules/bootstrap/dist/css/bootstrap.min.css';  


Step 8
Open terminal create component,
    ng g c employee-list  

Step 9
Open app.module.ts file and import httpModule
    import { BrowserModule } from '@angular/platform-browser';  
    import { NgModule } from '@angular/core';  
    import {HttpClientModule, HttpClient} from '@angular/common/http';  
      
    import { AppComponent } from './app.component';  
    import { from } from 'rxjs';  
    import { EmployeeListComponent } from './employee-list/employee-list.component';  
      
    @NgModule({  
      declarations: [  
        AppComponent,  
        EmployeeListComponent  
      ],  
      imports: [  
        BrowserModule,  
        HttpClientModule  
      ],  
      providers: [],  
      bootstrap: [AppComponent]  
    })  
    export class AppModule { }  


Step 10
Open employee-list component.ts file and add the following code,
    import { HttpClientModule, HttpClient } from '@angular/common/http';  
    import { Component, OnInit } from '@angular/core';  
      
    @Component({  
      selector: 'app-employee-list',  
      templateUrl: './employee-list.component.html',  
      styleUrls: ['./employee-list.component.css']  
    })  
    export class EmployeeListComponent implements OnInit {  
      
      constructor(private httpService: HttpClient) { }  
      employees: string[];  
      ngOnInit() {  
        this.httpService.get('http://localhost:52202/api/employee').subscribe(  
          data => {  
           this.employees = data as string [];  
          }  
        );  
      }  
      
    }  


Step 11
open employee-list.component.html and add the following code,
    <div class="container py-5">  
        <h3 class="text-center text-uppercase">List of Employees</h3>  
        <table class="table table-bordered table-striped">  
            <thead>  
                <tr class="text-center text-uppercase">  
                    <th>Employee ID</th>  
                    <th>First Name</th>  
                    <th>Last Name</th>  
                    <th>Salary</th>  
                    <th>Joining Date</th>  
                    <th>Department</th>  
                  </tr>  
            </thead>  
            <tbody>  
              <tr *ngFor="let emp of employees">  
                <td>{{emp.Employee_Id}}</td>  
                <td>{{emp.First_Name}}</td>  
                <td>{{emp.Last_Name}}</td>  
                <td>{{emp.Salary}}</td>  
                <td>{{emp.Joing_Date}}</td>  
                <td>{{emp.Department}}</td>  
              </tr>  
            </tbody>  
          </table>  
        </div>  


Step 12
Add your employee-list.component.html selector in app.component.html
    <app-employee-list></app-employee-list>  

Step 13
Run your project in browser.



AngularJS Hosting Europe - HostForLIFE :: New Development Site Angular

clock June 17, 2025 09:19 by author Peter

Note: The publication date of this article is January 10, 2025. This article series is unquestionably an AI result or byproduct.  This piece might represent a change in my writing style since it makes use of AI results that I understand, like those related to StackBlitz | Instant Dev Environments, to make it easier to write and easier to read. Angular first launched in 2016, Angular's home page used to be at angular.io for years. Recently, I found that a new Angular Development Site has been created. This article records some info about this event. 

Official Home: May, 2024

Previous Sites:
Angular - Introduction to the Angular docs --- Angular.io --- v17

Angular - Introduction to the Angular docs --- Angular.io --- v18


Tutorial:

Tutorials • Angular



AngularJS Hosting Europe - HostForLIFE :: Angular State Management with NGXS

clock June 12, 2025 10:33 by author Peter

Managing shared state between components gets more difficult as your Angular application expands.  NGXS (pronounced "nexus") offers a simple, intuitive, and powerful state management pattern for Angular apps, based on the principles of Redux but with a more Angular-friendly approach. This post will discuss how to effectively manage application state by configuring and utilizing NGXS.

Why NGXS?
NGXS provides:

  • A simple API using decorators and observables.
  • Type-safe state and actions.
  • Built-in support for plugins (logger, devtools, storage).
  • Easy-to-understand state mutation via actions.

Step 1. Install NGXS
Use the Angular CLI to install the NGXS packages:
npm install @ngxs/store --save


Optional DevTools and plugins:
npm install @ngxs/devtools-plugin @ngxs/logger-plugin --save

Step 2. Create a State Model
Create an interface to define your state:
// models/todo.model.ts
export interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

Step 3. Define Actions
Actions are plain classes that represent events in your app.

// actions/todo.actions.ts
export class AddTodo {
  static readonly type = '[TODO] Add';
  constructor(public payload: string) {}
}

export class ToggleTodo {
  static readonly type = '[TODO] Toggle';
  constructor(public id: number) {}
}

Step 4. Create the State
Define the NGXS state using the @State() decorator.
// state/todo.state.ts
import { State, Action, StateContext, Selector } from '@ngxs/store';
import { AddTodo, ToggleTodo } from '../actions/todo.actions';
import { Todo } from '../models/todo.model';

@State<Todo[]>({
  name: 'todos',
  defaults: []
})
export class TodoState {

  @Selector()
  static getTodos(state: Todo[]) {
    return state;
  }

  @Action(AddTodo)
  add({ getState, patchState }: StateContext<Todo[]>, { payload }: AddTodo) {
    const state = getState();
    const newTodo: Todo = { id: Date.now(), title: payload, completed: false };
    patchState([...state, newTodo]);
  }

  @Action(ToggleTodo)
  toggle({ getState, patchState }: StateContext<Todo[]>, { id }: ToggleTodo) {
    const state = getState();
    const updated = state.map(todo =>
      todo.id === id ? { ...todo, completed: !todo.completed } : todo
    );
    patchState(updated);
  }
}


Step 5. Register the State in the App Module

// app.module.ts
import { NgxsModule } from '@ngxs/store';
import { TodoState } from './state/todo.state';

@NgModule({
  declarations: [...],
  imports: [
    NgxsModule.forRoot([TodoState]),
  ],
  bootstrap: [...]
})
export class AppModule {}

Step 6. Use the State in Components
// app.component.ts
import { Store, Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { TodoState } from './state/todo.state';
import { AddTodo, ToggleTodo } from './actions/todo.actions';

@Component({...})
export class AppComponent {
  @Select(TodoState.getTodos) todos$: Observable<Todo[]>;

  constructor(private store: Store) {}

  addTodo(title: string) {
    this.store.dispatch(new AddTodo(title));
  }

  toggleTodo(id: number) {
    this.store.dispatch(new ToggleTodo(id));
  }
}

Conclusion
NGXS brings a clean and declarative way to manage state in Angular apps. With actions, selectors, and plugins, it streamlines complex state flows into something more maintainable and scalable. Happy coding !



AngularJS Hosting Europe - HostForLIFE :: How to Use Angular in the Signature Pad?

clock May 28, 2025 08:43 by author Peter

What is a Signature Pad?
A JavaScript package called Signature Pad might be used to create elegant signatures. It employs variable-width Bezier curve interpolation based on drum sander signatures as supplied by Square and supports HTML5 canvas. It does not take into account external libraries and functions in all of the main desktop and mobile browsers.

Let's begin with a real-world illustration. There are a number of npm packages that can be used for angular signatures, but in this case, I've picked "signature_pad" because I think it's quite simple to use and intuitive. Create the Angular Project app first, then adhere to the instructions below.

Step 1: Use the signature_pad JavaScript package to implement the associate degree example of Angular signature pad misuse. Installing the signature_pad library into our code should come first.

npm i signature_pad --save

Once install successfully then go ahead.

In the app.component.html template, we want to feature a canvas to draw our signature. it's 2 buttons. One to clear the signature space and another to urge the signature knowledge in Base64 string format.

We got to outline a canvas component to put in writing the signature. Once you have got the base64 signature, you'll show it as a picture exploitation of the template's IMG element.

Step 2: Let's add HTML code to our app.component.html, Please put the code as same as mine.
<div style="text-align: center;margin-top:30px;">
    <h3 style="font-family: monospace;">Signature Pad example by Peter</h3>
    <div style="margin-left: 39%;">
      <canvas #signPadCanvas (touchstart)="startSignPadDrawing($event)" (touchmove)="movedFinger($event)"></canvas>
    </div>
    <button class="btn btn-success" color="secondary" (click)="saveSignPad()">Save</button>
    <button class="btn btn-danger" (click)="clearSignPad()">Clear</button>
    <button class="btn btn-warning" (click)="undoSign()">Undo</button>
    <div>
      <span style="font-family: monospace;">Write the signature and click on Save</span>
      <div>
        <img src='{{ signImage }}' />
      </div>
    </div>
 </div>


Okay so now we need to add code to the app.component.ts file

Step 3:  Edit the app.component.ts typescript file code to draw the signature on the canvas and save it in base64 format.
First import SignaturePad from 'signature_pad' and ViewChild from '@angular/core'  as shown as below
import { Component, ViewChild  } from '@angular/core';
import SignaturePad from 'signature_pad';


Here I am putting whole the code of the component file, So please make sure it is exactly the same as below.

app.component.ts
import { Component, ViewChild  } from '@angular/core';
import SignaturePad from 'signature_pad';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'Signature Pad by Peter';
  signPad: any;
  @ViewChild('signPadCanvas', {static: false}) signaturePadElement:any;
  signImage:any;

  constructor() { }

  ngAfterViewInit() {
    this.signPad = new SignaturePad(this.signaturePadElement.nativeElement);
  }
  /*It's work in devices*/
  startSignPadDrawing(event: Event) {
    console.log(event);
  }
  /*It's work in devices*/
  movedFinger(event: Event) {
  }
  /*Undo last step from the signature*/
  undoSign() {
    const data = this.signPad.toData();
    if (data) {
      data.pop(); // remove the last step
      this.signPad.fromData(data);
    }
  }
  /*Clean whole the signature*/
  clearSignPad() {
    this.signPad.clear();
  }
  /*Here you can save the signature as a Image*/
  saveSignPad() {
    const base64ImageData = this.signPad.toDataURL();
    this.signImage = base64ImageData;
    //Here you can save your signature image using your API call.
  }
}


Step 4: After making the canvas element, add designs resembling borders, backgrounds, and so on to the canvas element. Let's put css into the app.component.scss file.
canvas {
  display: block;
  border: 1px solid rgb(105, 105, 105);
  background-color: var(--ion-color-success);
}
button {
  margin: 10px;
  margin-left: 10px;
}


All the code is done now let's run the application and see.

Note*:  You can add bootstrap CSS and js for better UI, See the below code and put into the index.html

index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Signature Pad by Peter</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>


You can write the signature under signature and click on the Save button and see.
Let's click on Save and see your signature as an Image, And If you want to clear the sign then click on the Clear button, and for undo click on Undo button. Here you can see the image of the written signature, You can save your signature into the database by using API.



AngularJS Hosting Europe - HostForLIFE :: Read Excel (XLSX) file in Angular 18

clock May 9, 2025 10:52 by author Peter

In this walk, you will learn the following things.

  • Create an angular project.
  • Install NPM Package XLSX
  • Restrict the user from uploading only the XLSX file to the input tag.
  • Restrict the user to select only one file at a time to upload.
  • Read Excel file (XLSX)
  • Get XLSX data in JSON format.

How is it implemented and how is it working in the description?

  • Create Angular project - AnguDemo.
  • Run the application and check project was created successfully.
  • Install NPM package called read-excel-file by command

npm install xlsx --save

  • Verify package is installed or not.
  • First, implement UI/Frontend side (HTML file) coding.
  • Component (TS file) coding.
  • Execute the Project
  • Output

Create an Angular Project called “AnguDemo” using the following CLI command.

Command

ng new AnguDemo

Example

CD AnguDemo
[Go inside project folder with the complete path]

Open Visual Studio code by using the following command.

Command

code

Example

Note. Visual Studio code will get started only if your system is configured with path and settings.

Before starting coding related WebCam first have to install a WebCam library called “ngx-webcam”.

Command
npm install xlsx --save

Example

How to cross-check whether check read-excel-file package is installed or not?
Open the Package.json file which is located in the root of the project folder. Inside the dependencies section, you can check the ‘read-excel-file’ entry with the version number marked in red color.

XLSX is a package from the SheetJS community. XLSX is an open-source and freeware solution for extracting useful data and generating new spreadsheets.


Click on Community Edition’s section Documentation button.


Now click on Demo Projects you will get so many tools and readymade code for XLSX files and other important topics.


Now we going to implement import Excel data.

Open the app.Component.html file and update the following code.
<p>Select XLSX File</p>

<input
  type="file"
  id="input"
  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
  (change)="onFileSubmit($event)"
  multiple="false"
/>

Let's Understand the above Input type=file command.

For Excel Files 97-2003 (.xls).
application/vnd.ms-excel

For Excel Files 2007+ (.xlsx).
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
multiple="false"


Only one will be allowed at a time not multiple.

Open the app.component.ts file and update the following code.
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';
import * as XLSX from "xlsx";
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, RouterLink],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular Demo';

  onFileSubmit(evt: any) {
    // File received
    const fileReced: DataTransfer = <DataTransfer>(evt.target);

    // Check how many files are received
    if (fileReced.files.length > 1) {
      alert('Only Single File allowed');
      return;
    } else {
      const reader: FileReader = new FileReader();

      reader.onload = (e: any) => {
        const binarystring: string = e.target.result;
        console.log(binarystring);

        const workbook: XLSX.WorkBook = XLSX.read(binarystring, { type: 'binary' });
        const worksheetname = workbook.SheetNames[0];
        const worksheet: XLSX.WorkSheet = workbook.Sheets[worksheetname];

        // Converting to JSON
        let excelsheetdata = (XLSX.utils.sheet_to_json(worksheet, { header: 1 }));

        // Print the Excel Data
        console.log(excelsheetdata);

        // You can use a loop to display the data on screen or process it as needed
      };

      reader.readAsArrayBuffer(fileReced.files[0]);
    }
  }
}


Now run the application by following the command.

Command
ng serve --open

Excel Data import was completed successfully.

Happy Coding!



AngularJS Hosting Europe - HostForLIFE :: Angular Component Selector Types with Examples

clock April 30, 2025 10:26 by author Peter

Selects are based on the HTML tag name. Example app-root. This type of selector you would be already familiar with as it is the default for all components in Angular.

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    RouterOutlet,
    AttributeSelectorComponent,
    MultipleAttributeSelectorComponent,
    AttributeSelectorWithValueComponent,
    CssClassSelectorComponent
  ],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
})
export class AppComponent {

}


Attribute Selector

  • The selector property in the @Component decorator specifies the selector for the component. In this case, we're using an attribute selector [app-attribute-selector].
  • To use the directive, you add the app-attribute-selector attribute to any HTML element in your template.
  • The content within that element will be replaced by the template defined in the directive.

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

    @Component({
      selector: '[app-attribute-selector]',
      standalone: true,
      imports: [],
      templateUrl: './attribute-selector.component.html',
      styleUrl: './attribute-selector.component.scss'
    })
    export class AttributeSelectorComponent {

    }

component view code
<p>attribute-selector works!</p>

Attribute selector with value

  • The selector property in the @Component decorator specifies the selector for the component. In this case, we're using an attribute selector [app-attribute-selector-with-value=” test”].
  • To use the directive, you add the app-attribute-selector-with-value=” test” attribute to any HTML element in your template.
  • The content within that element will be replaced by the template defined in the directive.

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

@Component({
  selector: '[app-attribute-selector-with-value="test"]',
  standalone: true,
  imports: [],
  templateUrl: './attribute-selector-with-value.component.html',
  styles: ``
})
export class AttributeSelectorWithValueComponent {

}

component view code
<p>attribute-selector-with-value works!</p>

The selector with multiple attributes

  • The selector property in the @Component decorator specifies the selector for the component. In this case, we're using an attribute selector [app-multiple-attribute-selector="test"][is-active].
  • To use the directive, you add the app-multiple-attribute-selector="test" is-active attribute to any HTML element in your template.
  • The content within that element will be replaced by the template defined in the directive.

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

@Component({
  selector: '[app-multiple-attribute-selector="test"][is-active]',
  standalone: true,
  imports: [],
  templateUrl: './multiple-attribute-selector.component.html',
  styleUrl: './multiple-attribute-selector.component.scss'
})
export class MultipleAttributeSelectorComponent {

}


component view code
<p>multiple-attribute-selector works!</p>

Key Points

  • Attribute selectors are useful when you want to apply a component to multiple elements based on a common attribute.
  • They are often used for directives that provide additional functionality to existing elements.
  • Attribute selectors are case-sensitive.

Note. For attribute values, Angular supports matching an exact attribute value with the equals (=) operator. Angular does not support other attribute value operators.
CSS Class Selector
 
Class selector
A CSS class selector is used to target elements that have a specific class attribute. The class attribute is defined within the opening tag of an HTML element and is preceded by a dot (.).
import { Component } from '@angular/core';

@Component({
  selector: '.app-css-class-selector',
  standalone: true,
  imports: [],
  templateUrl: './css-class-selector.component.html',
  styles: ``
})
export class CssClassSelectorComponent {

}


component view code
<p>css-class-selector works!</p>

:not pseudo-class
The: not pseudo-class in CSS allows you to target elements that do not match a specific selector. You can leverage this in Angular component selectors to create more targeted components.

Explanation
The :not(.disabled) part of the selector ensures that the component only matches elements with the class "container" that do not also have the class "disabled".
This provides a way to conditionally apply the component based on the presence or absence of other classes.
import { Component } from '@angular/core';

@Component({
  selector: '.app-css-not-pseudo-selector:not(.disabled)',
  standalone: true,
  imports: [],
  templateUrl: './css-not-pseudo-selector.component.html',
  styles: ``
})
export class CssNotPseudoSelectorComponent {

}


component view code
<p>css-not-pseudo-selector works!</p>

Targeting elements that are not direct children of a specific element.
@Component({
  selector: 'div:not(.parent) > p'
})
export class MyComponent {
}

Targeting elements that do not have a specific attribute.
@Component({
  selector: 'button:not([disabled])'
})
export class MyButtonComponent {
}


Key Points

  • The :not pseudo-class can be combined with other selectors to create more complex targeting rules.
  • It's a powerful tool for creating reusable components that can be applied conditionally based on the structure of your HTML.
  • Be cautious when using :not with complex selectors, as it can sometimes lead to unexpected behavior if not used correctly.

By understanding and utilizing the : not pseudo-class, you can create more flexible and targeted components in your Angular applications.

Combining selectors

You can combine selectors in Angular using CSS-like syntax to create more specific targeting rules. Here are some examples. You can combine with Element, class, id, pseudo-class, attributes, comma-separated selectors, and so on.

Combining by Element, Class, and ID
@Component({
  selector: 'div.container#my-container'
})
export class MyComponent {
}


This component will only match elements that are.

  • A div element
  • Have the class container
  • Have the ID my-container

Combining with Pseudo-Classes
@Component({
  selector: 'button:not(.disabled):hover'
})
export class MyButtonComponent {
}


This component will match buttons that.

  • Do not have the class disabled
  • Are being hovered over

Combining with Attributes
@Component({
  selector: '[data-type="product"][is-active]'
})
export class ActiveProductComponent {
}


This component will match elements that.

  • Have the attribute data type with the value "product"
  • Have the attribute is-active

Combining Multiple Selectors
You can combine multiple selectors using commas.
@Component({
  selector: '.container, .card'
})
export class MyComponent {
}


This component will match elements that have either the class container or the class card.

Remember

  • Specificity: The more specific your selector is, the higher its priority.
  • Cascading Stylesheets (CSS): If multiple selectors match an element, the most specific selector takes precedence.
  • HTML Structure: Ensure that your selectors match the structure of your HTML elements.

By effectively combining selectors, you can create targeted components that accurately match the elements you intend to interact with in your Angular application.

Below is the output of the Selectors explained above.

App.component.ts

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { AttributeSelectorComponent } from './attribute-selector/attribute-selector.component';
import { MultipleAttributeSelectorComponent } from './multiple-attribute-selector/multiple-attribute-selector.component';
import { AttributeSelectorWithValueComponent } from './attribute-selector-with-value/attribute-selector-with-value.component';
import { CssClassSelectorComponent } from './css-class-selector/css-class-selector.component';
import { CssNotPseudoSelectorComponent } from './css-not-pseudo-selector/css-not-pseudo-selector.component';
import { CombiningSelectorsComponent } from './combining-selectors/combining-selectors.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    RouterOutlet,
    AttributeSelectorComponent,
    MultipleAttributeSelectorComponent,
    AttributeSelectorWithValueComponent,
    CssClassSelectorComponent,
    CssNotPseudoSelectorComponent,
    CombiningSelectorsComponent
  ],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
})
export class AppComponent {
  show = false;
  testId = 'main-cta';
  title = 'angular-dev-test';
}


component view code
@if(show){
<button [attr.data-test-id]="testId">Show CTA</button>
} @else {
<button [attr.data-test-id]="testId">Normal CTA</button>
}

<div app-attribute-selector is-active>will be ignored</div>
<div app-attribute-selector-with-value="test">will be ignored</div>
<div app-multiple-attribute-selector="test" is-active>will be ignored</div>
<div class="app-css-class-selector">will be ignored</div>
<div class="app-css-not-pseudo-selector">will be ignored</div>
<button type="reset">Reset</button>



AngularJS Hosting Europe - HostForLIFE :: Angular 2 Bind DropDown List Using Web API

clock April 23, 2025 09:18 by author Peter

The app.component.ts file, which contains the code to bind the dropdown list, is where we will call the external HTML file after creating the project in Visual Studio.


Requirements
Since I created the models in this application using the Database First approach, I'm assuming you know how to utilize an entity framework to retrieve and save the data. To store the data for our languages, create a table in the SQL Server database. See the table script provided below.

CREATE TABLE [dbo].[tbl_language] (
    [languageID] INT IDENTITY(1,1) NOT NULL,
    [language] VARCHAR(200) NOT NULL,
    CONSTRAINT [PK_TBL_LANGUAGE] PRIMARY KEY CLUSTERED (
        [languageID] ASC
    ) WITH (
        PAD_INDEX = OFF,
        STATISTICS_NORECOMPUTE = OFF,
        IGNORE_DUP_KEY = OFF,
        ALLOW_ROW_LOCKS = ON,
        ALLOW_PAGE_LOCKS = ON
    ) ON [PRIMARY]
) ON [PRIMARY];

Insert some sample data into the table.

app.component.ts
import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: './app/binddropdownlisteg.html'
})
export class AppComponent {
}


“app.Component.ts” is the file, which is available for you when you have created your Angular 2 app in an app/app.component.ts file.

Now, create an empty Web API Controller in your Visual Studio by right-clicking on the project - > Add new item - > select Empty Web API Controller from Visual Studio.

Add the code given below, where the Web API Controller is required to get the list of the languages from the table.

Web API Controller and Method
public class languageAPIController : ApiController
{
    private db_sampleentities db = new db_sampleentities();

    // Constructor
    public languageAPIController()
    {
        // Add the following code
        // Problem will be solved
        db.Configuration.ProxyCreationEnabled = false;
    }

    // GET: api/languageAPI
    public IEnumerable<tbl_language> Gettbl_language()
    {
        return db.tbl_language.ToList();
    }
}

Here, in the code db_sampleentities given above is the datacontext class, which is used to communicate with the SQL Server database to fetch the records from the database.

“tbl_language“ is the model, which will hold properties “languageID” and “language” to map with the table tbl_language columns, which we have created in the database.
Service

Create a new TypeScript file in Visual Studio with the name languageservice.service.ts, which acts as a Service for us to call the Web API method and map the data in JSON format.

languageservice.service.ts
import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { tbl_language } from '../service_models/samplemodels';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class languageService {
    constructor(private http: Http) { }

    getlanguages(): Observable<tbl_language[]> {
        return this.http.get('api/languageAPI')
            .map(res => res.json())
            .catch(this.handleError);
    }

    private handleError(error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}


The code above lets you connect to the Web API method(Getbl_language()) to extract the languages.

binddropdownlisteg.html
Create an HTML file in the Application to display the dropdown, and add the code given below, which will fetch the data by looping through the language data.
<div>
    <label>Language:</label>
    <select [formControl]="sampleform.controls['languageID']">
        <option value="0">--Select--</option>
        <option *ngFor="let lang of languages" value="{{ lang.languageID }}">
            {{ lang.language }}
        </option>
    </select>
</div>


Service Model

Create a TypeScript file and name it languagemodel.ts, which has properties to hold the data from Web API.

languagemodel.ts
export class tbl_language {
    languageID: number;
    language: string;
}


Now, open an app.component.ts file and change the code to include the Service and Model, which we have created in an AppComponent class to bind the dropdown list.

Final Code for app.component.ts file
import { Component } from '@angular/core';

// * Import the language model which contains properties for holding the data
import { tbl_language } from '../Models/languagemodel';

// * Import the name of the service we have created
import { languageService } from '../Services/languageservice.service';
import { FormBuilder, Validators, FormGroup, FormControl } from '@angular/forms';

@Component({
    selector: 'my-app',
    templateUrl: './app/binddropdownlisteg.html',
    providers: [languageService]
})
export class AppComponent {
    errorMessage: string;

    public languages: tbl_language[]; // Create a variable of type tbl_language object
    sampleform: FormGroup;

    constructor(private _languageService: languageService, fb: FormBuilder) {
        this.sampleform = fb.group({
            'languageID': [null] // Will use the property in HTML page
        });
    }

    ngOnInit() {
        // Call the method on initial load of page to bind dropdown
        this.getlanguages();
    }

    // Get the list of languages
    getlanguages() {
        this._languageService.getlanguages().subscribe(
            res => this.languages = res,
            error => this.errorMessage = <any>error
        );
    }
}

Summary
Run the Application by pressing F5 and you can see the output with the the values drowndown list. In this tutorial, we created a table with the languages, a Web API method to fetch the languages, subscribed to the data in Angular 2, and displayed on the screen by binding the data to the dropdown list.



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