Full Trust European Hosting

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

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.



AngularJS Hosting Europe - HostForLIFE :: Use AngularJS to Make an AJAX Call and Get a JSON Response

clock April 10, 2025 08:20 by author Peter

This article describes how to use AngularJS to retrieve data in JSON format. Actually, I was attempting to use AngularJS to make an AJAX request to a web service. I tried this code for that.

<script>
    var myapp = angular.module('myApp', []);

    myapp.controller('control', function ($scope, $http) {
        var call = "WebService1.asmx/HelloWorld";

        $http.post(call)
            .success(function (response) {
                $scope.value = response;
            })
            .error(function (error) {
                alert(error);
            });
    });
</script>

At the WebService I created a method that was returning a string, here I am just using Hello World which is provided in each WebService by default.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
}


After making the call I bound the value into a span using ng-bind.
<body>
    <form id="form1" runat="server">
        <div ng-app="myApp" ng-controller="control">
            <span ng-bind="value"></span>
        </div>
    </form>
</body>


On running the code I got an output like this.

This was not the output I was expecting, I realized that the data was not coming in JSON format, so I had two possible solutions, either return the data from the WebService after converting it to JSON or make every incoming data JSON using AngularJS, I chose the second and changed the code to be as in the following.

<script>
    var myapp = angular.module('myApp', []);

    myapp.controller('control', function ($scope, $http) {
        $http({
            url: "WebService1.asmx/HelloWorld",
            dataType: 'json',
            method: 'POST',
            data: '',
            headers: {
                "Content-Type": "application/json"
            }
        })
        .success(function (response) {
            $scope.value = response.d;
        })
        .error(function (error) {
            alert(error);
        });
    });
</script>


Now, you can see that the call is looking something like an AJAX call made using jQuery but it's from AngularJS, so some of you might feel that this way of calling is easier than the previous one but It's just the extended version of the previous call. Here I have added the success and error functions so that I could determine what type of error I am getting if the code is not working.

Now, we can run the code and see the output.

Now, we are getting the expected result. The source code is available at the top of article.



AngularJS Hosting Europe - HostForLIFE :: Effective Data Management with RxJS Observables in Angular 16

clock March 27, 2025 09:19 by author Peter

Discover how Angular 16 and RxJS Observables work together to effectively manage asynchronous data streams. This post explores important ideas, shows how to apply them to Angular 16 projects, and identifies best practices. To assist you in determining when and when to use observables for the requirements of your application, we also go over the benefits and drawbacks of doing so.

 

Key Concepts and Examples
Creating an Observable

import { Observable } from 'rxjs';
const myObservable = new Observable((observer) => {
  observer.next('First value');
  observer.next('Second value');
  observer.complete();
});
// Subscribing to the Observable
myObservable.subscribe({
  next: (value) => console.log(value),
  complete: () => console.log('Observable completed!'),
});

Using HttpClient with Observables
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
  selector: 'app-user-list',
  template: `
    <div *ngFor="let user of users">
      {{ user.name }}
    </div>
  `,
})
export class UserListComponent {
  users: any[] = [];
  constructor(private http: HttpClient) {
    this.http.get('https://jsonplaceholder.typicode.com/users')
      .subscribe((data) => {
        this.users = data as any[];
      });
  }
}


Chaining Operators
import { of } from 'rxjs';
import { map, filter } from 'rxjs/operators';
of(1, 2, 3, 4, 5)
  .pipe(
    filter((num) => num % 2 === 0), // Only even numbers
    map((num) => num * 10)          // Multiply by 10
  )
  .subscribe((result) => console.log(result)); // Output: 20, 40

Pros of Using RxJS Observables in Angular

1. Reactive Architecture
Example: Handling real-time data streams from WebSocket.

import { webSocket } from 'rxjs/webSocket';
const socket$ = webSocket('wss://example.com/socket');
socket$.subscribe((data) =>
  console.log('Message from server:', data)
);

2. Declarative Code
Example: Combining multiple streams


import { interval, combineLatest } from 'rxjs';
const timer1$ = interval(1000);
const timer2$ = interval(1500);
combineLatest([timer1$, timer2$]).subscribe(([val1, val2]) =>
  console.log(`Timer1: ${val1}, Timer2: ${val2}`)
);


3. Seamless Integration with Angular: Angular’s AsyncPipe automatically handles subscriptions and unsubscriptions.
<div *ngIf="(http.get('https://jsonplaceholder.typicode.com/posts') | async) as posts">
  <ul>
    <li *ngFor="let post of posts">
      {{ post.title }}
    </li>
  </ul>
</div>


Cons of Using RxJS Observables in Angular

1. Steep Learning Curve

  • Challenge: Understanding operators like switchMap vs. mergeMap.
  • Example of switchMap: Cancels previous HTTP requests when a new one starts.

searchInput.valueChanges
  .pipe(
    switchMap((query) =>
      this.http.get(`/search?q=${query}`)
    )
  )
  .subscribe((results) =>
    console.log(results)
  );


2. Potential Overhead: Always unsubscribe from streams

this.http
  .get('/api/data')
  .toPromise()
  .then((data) => console.log(data));


3. Memory Leaks: Always unsubscribe from streams

import { Component, OnDestroy } from '@angular/core';
import { Subscription, interval } from 'rxjs';
@Component({
  selector: 'app-example',
  template: '',
})
export class ExampleComponent implements OnDestroy {
  private subscription: Subscription;
  constructor() {
    this.subscription = interval(1000).subscribe(console.log);
  }
  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}



Node.js Hosting - HostForLIFE :: Node.js API Design with the Power of Design Patterns

clock March 25, 2025 08:36 by author Peter

One of the most powerful tools for creating scalable and effective APIs is Node.js. Node.js's ability to manage asynchronous tasks well is one of the main reasons for its success. But as projects get more complicated, it becomes crucial to keep the code clear, scalable, and tidy. Design patterns are useful in this situation because they provide tried-and-true answers to typical development problems.


We'll explore some popular design patterns in the context of developing Node.js APIs in this post, along with useful code samples.

1. Singleton Pattern
The Singleton pattern ensures that a class has only one instance and provides a global point to access it. In a Node.js API, this can be beneficial for managing shared resources or configurations.

class Singleton {
  constructor() {

    if (!Singleton.instance) {
      Singleton.instance = this;
    }
    return Singleton.instance;

  }
  // Your class methods here
}

const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // Output: true


The Singleton pattern becomes handy when you want a single point of control for certain aspects of your API, such as managing a shared connection pool or configuration settings.

2. Factory Pattern

The Factory pattern is useful when you want to delegate the responsibility of instantiating objects to a separate factory class. This promotes code separation and flexibility in creating instances.
class Product {

  constructor(name) {
    this.name = name;

  }
}

class ProductFactory {
  createProduct(name) {
    return new Product(name);
  }
}

const productFactory = new ProductFactory();
const product = productFactory.createProduct('Sample Product');

In an API, the Factory pattern can be employed to encapsulate the logic of creating complex objects, allowing for better maintenance and extensibility.

3. Middleware Pattern

In Node.js, middleware plays a pivotal role in processing incoming requests. The middleware pattern involves a chain of functions, each responsible for handling a specific aspect of the request-response cycle.

const middleware1 = (req, res, next) => {

  // Do something before passing control to the next middleware
  next();

};
const middleware2 = (req, res, next) => {

  // Do something else
  next();
};

app.use(middleware1);
app.use(middleware2);

The Middleware pattern in Node.js is crucial for modularizing your API's logic, making it easier to manage and extend as your project evolves.

4. Observer Pattern

The Observer pattern is ideal for implementing event handling mechanisms. In a Node.js API, this can be applied to handle events like data updates or user actions.

class Observer {

  constructor() {
    this.observers = [];
  }

  subscribe(fn) {
    this.observers.push(fn);
  }

  unsubscribe(fn) {
    this.observers = this.observers.filter(subscriber => subscriber !== fn);
  }

  notify(data) {
    this.observers.forEach(observer => observer(data));
  }
}

const dataObserver = new Observer();
dataObserver.subscribe(data => {
  console.log(`Data updated: ${data}`);
});

dataObserver.notify('New data');

The Observer pattern facilitates the creation of loosely coupled components in your API, allowing for better scalability and maintainability.

5. Repository Pattern

The Repository pattern abstracts the data access layer from the business logic. This is particularly beneficial for managing database interactions in a Node.js API.
class UserRepository {

  constructor(database) {
    this.database = database;
  }

  getUserById(userId) {
    return this.database.query(`SELECT * FROM users WHERE id = ${userId}`);
  }

  saveUser(user) {
    return this.database.query('INSERT INTO users SET ?', user);
  }
}

const db = /* your database connection */;
const userRepository = new UserRepository(db);
const user = { name: 'John Doe', email: '[email protected]' };
userRepository.saveUser(user);

The Repository pattern aids in decoupling your API's business logic from the underlying data storage, facilitating easier testing and maintenance.

Conclusion

Incorporating design patterns in your Node.js API can greatly enhance its architecture, making it more maintainable and scalable. The examples provided above cover just a glimpse of the design patterns available for Node.js development. As you continue to explore and implement these patterns, you'll find your code becoming more modular, flexible, and easier to maintain.

Design patterns are powerful tools in the hands of developers, providing effective solutions to common problems encountered in API development. By adopting these patterns judiciously, you can ensure the long-term success and sustainability of your Node.js API projects.




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