Full Trust European Hosting

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

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();
  }
}



AngularJS Hosting Europe - HostForLIFE :: Configure Build Environments With Angular

clock March 13, 2025 08:36 by author Peter

Managing various settings and configurations for development, staging, production, or any other environment requires the ability to configure build environments in Angular. Through the environments folder and the angular.json file, Angular offers an integrated solution for this.

To set up build environments in an Angular application, follow these steps.

Step 1: Establish the project
ng new my-angular-app

Step 2. Create Environment Files
Angular typically comes with two environment files out of the box.

  • src/environments/environment.ts (for development)
  • src/environments/environment.prod.ts (for production)

You can create additional files for other environments (e.g., staging)

Each file exports an object with environment-specific properties.
// environment.ts (development)
export const environment = {
  production: false,
  apiBaseUrl: 'http://localhost:4000/api',
};

// environment.prod.ts (production)
export const environment = {
  production: true,
  apiBaseUrl: 'https://api.example.com',
};

// environment.staging.ts (staging)
export const environment = {
  production: false,
  apiBaseUrl: 'https://staging-api.example.com',
};

Step 3. Configure File Replacements
Modify the angular.json file to specify file replacements for different build configurations.
Locate the fileReplacements section under the configurations key in your Angular project.
"configurations": {
  "production": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod.ts"
      }
    ]
  },
  "staging": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.staging.ts"
      }
    ]
  }
}

Step 4. Add Build Scripts
Update the angular.json file to define build configurations for new environments.
"architect": {
  "build": {
    "configurations": {
      "production": {
        ...
      },
      "staging": {
        "fileReplacements": [
          {
            "replace": "src/environments/environment.ts",
            "with": "src/environments/environment.staging.ts"
          }
        ],
        "optimization": true,
        "outputHashing": "all",
        "sourceMap": false,
        "extractCss": true,
        "namedChunks": false,
        "aot": true,
        "buildOptimizer": true,
        "budgets": [
          {
            "type": "initial",
            "maximumWarning": "2mb",
            "maximumError": "5mb"
          }
        ]
      }
    }
  }
}


Step 5. Build for Specific Environments
Use the --configuration flag to build for specific environments.
ng build --configuration=staging
ng build --configuration=production

For development, the default build configuration applies unless overridden.

Step 6. Use Environment Variables in Code
In your Angular code, use the environment object to access environment-specific values.
import { environment } from '../environments/environment';
console.log('API Base URL:', environment.apiBaseUrl);
if (environment.production) {
  console.log('Running in production mode');
}


Step 7. Add Additional Settings
For complex builds, you can.

  • Use environment variables with tools like dotenv for dynamic replacements.
  • Integrate third-party CI/CD tools to manage deployment-specific configurations.

By following these steps, you can manage multiple build environments efficiently in your Angular application. Let me know if you'd like further assistance or an example.



AngularJS Hosting Europe - HostForLIFE :: Function-Based Interceptor in Angular

clock February 5, 2025 06:09 by author Peter

An excellent method for managing and altering HTTP requests and answers across your application is to use Angular interceptors. Although classes are typically used to build interceptors, function-based interceptors can be used for more straightforward and reusable code.


We'll go over how to make and use function-based interceptors in Angular in this blog, along with simple examples for increased flexibility and clarity.

What is a function-based Interceptor?
A function-based interceptor is a simpler and more flexible option compared to a class-based interceptor. Instead of creating a whole class with an intercept method, you put your logic into individual functions. This approach helps with,

  • Separation of Concerns: Smaller, focused functions are easier to test and maintain.
  • Reusability: You can reuse the interceptor logic by sharing or combining multiple functions.

Benefits of Function-Based Interceptors

  • Less Setup: You only need a function, not an entire class.
  • Easier Testing: It’s simpler to test individual functions.
  • Flexible: You can combine several functions to handle complex request/response processes.

How to implement a function-based Interceptor?
Let us create an angular project with the imported HttpClientModule.
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpClientModule } from '@angular/common/http';
    import { AppComponent } from './app.component';

    @NgModule({
      declarations: [AppComponent],
      imports: [BrowserModule, HttpClientModule],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

TypeScript
Create a function-based interceptor - a function-based interceptor works by using a factory to handle the request/response logic.

import { HttpInterceptorFn } from '@angular/common/http';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  console.log('Intercepting Request:', req);

  // Add an Authorization header
  const token = 'your-token-here';
  const clonedRequest = req.clone({
    setHeaders: {
      Authorization: `Bearer ${token}`,
    },
  });

  console.log('Modified Request:', clonedRequest);

  // Forward the modified request
  return next(clonedRequest);
};


Key Points

  • Factory Function: Use HttpInterceptorFn to define the interceptor.
  • Modify Request: Use req.clone() to create a modified version of the request.
  • Forward Request: Send the cloned request to the next step with next.

Register the Function Interceptor
To register the function-based interceptor, use the provided HTTP client configuration in your AppModule or feature module.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './auth-interceptor.fn';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [
    provideHttpClient(withInterceptors([authInterceptor]))
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Why Use provideHttpClient?
Introduced in Angular 15, this modern API makes it easier to configure the HTTP client and supports function-based interceptors directly.

Use the Interceptor in an HTTP Request

Now that the interceptor is registered test it by making an HTTP request.
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'function-based-Interceptor';

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe((data) => {
      console.log('Response:', data);
    });
  }
}


Let us execute the app and validate whether the interceptor was properly executed.



AngularJS Hosting Europe - HostForLIFE :: Understanding the Angular Lifecycle Hooks

clock January 22, 2025 08:17 by author Peter

In Angular, components go through a series of stages from their creation to destruction. These stages are collectively known as the Angular lifecycle. Understanding the lifecycle hooks provided by Angular allows developers to tap into key moments in a component's lifecycle to perform initialization, cleanup, and other crucial operations. This article provides an in-depth look at each of these lifecycle hooks and how to use them effectively.

Angular Lifecycle Hooks
Here is a list of the primary lifecycle hooks in Angular.

  • ngOnChanges
  • ngOnInit
  • ngDoCheck
  • ngAfterContentInit
  • ngAfterContentChecked
  • ngAfterViewInit
  • ngAfterViewChecked
  • ngOnDestroy

Let's explore each of these hooks in detail.

1. ngOnChanges

When it’s called: This hook is called whenever an input property bound to a component changes. It’s called before ngOnInit and whenever the input properties are updated.
Use case: Use ngOnChanges to act on changes to input properties from the parent component.

Example
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
  selector: 'app-child',
  template: '<p>{{data}}</p>',
})
export class ChildComponent implements OnChanges {
  @Input() data: string;
  ngOnChanges(changes: SimpleChanges) {
    console.log('ngOnChanges called', changes);
  }
}


2. ngOnInit
When it’s called: This hook is called once, after the first ngOnChanges. It’s typically used for component initialization.
Use case: Use ngOnInit to perform component initialization, like fetching data.

Example
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-example',
  template: '<p>Example works!</p>',
})
export class ExampleComponent implements OnInit {
  ngOnInit() {
    console.log('ngOnInit called');
  }
}


3. ngDoCheck
When it’s called: This hook is called during every change detection run. It’s useful for custom change detection.
Use case: Use ngDoCheck to implement custom change detection logic.

Example
import { Component, DoCheck } from '@angular/core';
@Component({
  selector: 'app-check',
  template: '<p>Check works!</p>',
})
export class CheckComponent implements DoCheck {
  ngDoCheck() {
    console.log('ngDoCheck called');
  }
}


4. ngAfterContentInit
When it’s called: This hook is called after Angular projects external content into the component’s view (ng-content).
Use case: Use ngAfterContentInit to respond to content projection into the component.

Example
import { Component, AfterContentInit } from '@angular/core';
@Component({
  selector: 'app-content',
  template: '<ng-content></ng-content>',
})
export class ContentComponent implements AfterContentInit {
  ngAfterContentInit() {
    console.log('ngAfterContentInit called');
  }
}


5. ngAfterContentChecked
When it’s called: This hook is called after every check of the component’s projected content.
Use case: Use ngAfterContentChecked to act after the content is checked.

Example
import { Component, AfterContentChecked } from '@angular/core';
@Component({
  selector: 'app-content-check',
  template: '<ng-content></ng-content>',
})
export class ContentCheckComponent implements AfterContentChecked {
  ngAfterContentChecked() {
    console.log('ngAfterContentChecked called');
  }
}


6. ngAfterViewInit
When it’s called: This hook is called after Angular initializes the component’s views and child views.
Use case: Use ngAfterViewInit to perform actions after the component’s view is initialized.

Example
import { Component, AfterViewInit } from '@angular/core';
@Component({
  selector: 'app-view-init',
  template: '<p>View Init works!</p>',
})
export class ViewInitComponent implements AfterViewInit {
  ngAfterViewInit() {
    console.log('ngAfterViewInit called');
  }
}


7. ngAfterViewChecked
When it’s called: This hook is called after every check of the component’s view.
Use case: Use ngAfterViewChecked to act after the component’s view is checked.

Example
import { Component, AfterViewChecked } from '@angular/core';
@Component({
  selector: 'app-view-check',
  template: '<p>View Check works!</p>',
})
export class ViewCheckComponent implements AfterViewChecked {
  ngAfterViewChecked() {
    console.log('ngAfterViewChecked called');
  }
}

8. ngOnDestroy
When it’s called: This hook is called just before Angular destroys the component.
Use case: Use ngOnDestroy for cleanup, like unsubscribing from observables and detaching event handlers.

Example
import { Component, OnDestroy } from '@angular/core';
@Component({
  selector: 'app-destroy',
  template: '<p>Destroy works!</p>',
})
export class DestroyComponent implements OnDestroy {
  ngOnDestroy() {
    console.log('ngOnDestroy called');
  }
}

Lifecycle Sequence
Understanding the order of these hooks is crucial for correctly implementing logic that depends on the component's lifecycle stages.

  • ngOnChanges
  • ngOnInit
  • ngDoCheck
  • ngAfterContentInit
  • ngAfterContentChecked
  • ngAfterViewInit
  • ngAfterViewChecked
  • ngOnDestroy

Practical Use Cases

  • ngOnInit: Ideal for initialization tasks like fetching data from a service.
  • ngOnChanges: Useful for reacting to changes in input properties.
  • ngOnDestroy: Perfect for cleaning up resources, like unsubscribing from observables.
  • ngAfterViewInit: Great for manipulating the DOM after the view is initialized.

Conclusion
Mastering Angular lifecycle hooks is essential for building robust and maintainable Angular applications. By understanding when and how to use each hook, developers can ensure their components are properly initialized, updated, and cleaned up. This not only leads to better performance but also improves code organization and readability.



AngularJS Hosting Europe - HostForLIFE :: Angular Routing Mastery Navigate Between Components Easily

clock August 16, 2024 09:34 by author Peter

Routing in Angular enables you to move between several parts (or views) in a single-page application (SPA). To do this, routes that associate URL pathways with particular components are built up. The relevant component loads and displays in a preset area of your application (typically designated by a <router-outlet>) when a user navigates to a URL.


to use the robust routing system of Angular to move between components in an efficient manner. This article covers everything from configuring routes to using Angular's Router service programmatically and utilizing RouterLink for template-based navigation. You will learn how to map URLs to components and render them dynamically using <router-outlet>, providing smooth navigation inside your Angular applications, with concise explanations and functional code examples.

Key Concepts

  1. Router Module: This is Angular's mechanism for handling routing. You define the routes in a routing module (often AppRoutingModule), where each route maps a URL path to a component.
  2. RouterLink Directive: This directive is used in HTML templates to bind a URL to an anchor tag or button. When clicked, Angular will navigate to the route specified by the RouterLink.
  3. Router Service: This service provides methods to navigate to a route programmatically from within a component’s TypeScript file.
  4. Router Outlet: This is a directive that acts as a placeholder where the routed component will be rendered.

Step-by-Step Implementation with Code Example
1. Setting Up Routes

First, create your components if you haven't already.
ng generate component component-a
ng generate component component-b


Then, define the routes in the AppRoutingModule.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ComponentA } from './component-a/component-a.component';
import { ComponentB } from './component-b/component-b.component';

const routes: Routes = [
  { path: 'component-a', component: ComponentA },
  { path: 'component-b', component: ComponentB },
  { path: '', redirectTo: '/component-a', pathMatch: 'full' }  // Default route
];

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

2. Navigating Using RouterLink

In ComponentA, you can create a link that navigates to ComponentB.
<!-- component-a.component.html -->
<h2>This is Component A</h2>
<a [routerLink]="['/component-b']">Go to Component B</a>


When the user clicks on this link, Angular will navigate to /component-b and load ComponentB into the router outlet.

3. Navigating Programmatically Using the Router Service

You can also navigate programmatically from within a component’s TypeScript file.

// component-a.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-component-a',
  templateUrl: './component-a.component.html',
  styleUrls: ['./component-a.component.css']
})
export class ComponentA {

  constructor(private router: Router) { }

  goToComponentB() {
    this.router.navigate(['/component-b']);
  }
}


In the corresponding HTML.
<!-- component-a.component.html -->
<h2>This is Component A</h2>
<button (click)="goToComponentB()">Go to Component B</button>


4. Using Router Outlet
Ensure you have a <router-outlet> in your main HTML template (usually app.component.html).
<!-- app.component.html -->
<router-outlet></router-outlet>

This directive is where the routed components will be displayed based on the URL.

5. Putting It All Together

Here’s how everything ties together.

  • AppRoutingModule: Defines the routes.
  • ComponentA: Has a link and a button to navigate to ComponentB.
  • ComponentB: Displays content when navigated to.

Example Code Structure// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ComponentA } from './component-a/component-a.component';
import { ComponentB } from './component-b/component-b.component';

const routes: Routes = [
  { path: 'component-a', component: ComponentA },
  { path: 'component-b', component: ComponentB },
  { path: '', redirectTo: '/component-a', pathMatch: 'full' }  // Default route
];

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

// component-a.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-component-a',
  templateUrl: './component-a.component.html',
  styleUrls: ['./component-a.component.css']
})
export class ComponentA {

  constructor(private router: Router) { }

  goToComponentB() {
    this.router.navigate(['/component-b']);
  }
}

// component-a.component.html
<h2>This is Component A</h2>
<a [routerLink]="['/component-b']">Go to Component B</a>
<button (click)="goToComponentB()">Go to Component B</button>

// component-b.component.html
<h2>This is Component B</h2>

// app.component.html
<router-outlet></router-outlet>

Summary

  • Routes: Define in AppRoutingModule to map URLs to components.
  • RouterLink: Use templates for simple navigation.
  • Router Service: Use for programmatic navigation in TypeScript.
  • Router Outlet: The placeholder for rendering routed components.

This setup allows you to navigate between components effectively, using both template-based and programmatic methods in Angular.



AngularJS Hosting Europe - HostForLIFE :: Harnessing the Power of Environments using Angular

clock August 5, 2024 08:40 by author Peter

Ever pondered how to call multiple APIs, colors, or headlines for the same application from several environments? Production APIs and test APIs are undoubtedly distinct and need to be utilized extremely carefully. When launching a project, we won't manually alter every API call and sentence structure. This is dangerous and should not be done. With Angular, it's simple to have distinct setups for various environments. Because of this, we can use and deploy to as many environments and stages as necessary without ever having to alter the code. Environment files is the name of it.


To put it briefly, we can have two environment files: environment.development.ts for the development stage and environment.ts for the production stage. The appropriate environment file will then be used, based on where we are distributing our program.

There are very few configurations needed, and there is a significant gain. I'll walk you through the process in this post and give an example of using various texts and APIs.

Getting started
Create a new app: ng new angular-environment-demo --standalone false.
Generate environment files: ng generate environments.

Note. As from the Angular 15.1 environment files are not generated automatically.

Environment file hierarchy
The identical item will initially be present in both the environments.ts and the environments.development.ts. Both objects should have the same key and all settings should be done with them.

For example, you have the following in that file if the environment.development.ts has a key-value pair like: "weather_status": "Good" and the environment.ts will not utilize it. The weather status is ''. This is due to the fact that you are using it in the code, and your code will utilize [this will be explained later] when it looks for it in the environment file. Compilation errors result from your code still searching for this even if it is pointing to another environment file.

Let's create two distinct page titles.

You can utilize the environment file's values in the app.component.ts file or any other ts file by accessing them as follows: environment.\<value you wish to access.>>. Here's an illustration of how to use the pageTitle in the app.component.ts ngOnInit.

Notice the import on line 2. For now, you can import any of the environment files. On line 13, we are assigning the value of ‘pageTitle’ from the environment to ‘this. title’. In the HTML file, we are using the ‘title’ as below.

When you serve the application using: ng serve, you will be given the following screen.

When we do only: “ng serve”, the values from the ‘environment.development.ts’ file are used. If you want to use the configurations from the environment.ts file, you should add the following in the angular.json file.

"fileReplacements": [
  {
    "replace": "src/environments/environment.development.ts",
    "with": "src/environments/environment.ts"
  }
],


These codes should be added under "projects" -> "architect" -> "build" -> "configurations" -> "production" in the angular.json file. Below is a full example of the angular.json file:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "angular-environment-demo": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "standalone": false
        },
        "@schematics/angular:directive": {
          "standalone": false
        },
        "@schematics/angular:pipe": {
          "standalone": false
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:application",
          "options": {
            "outputPath": "dist/angular-environment-demo",
            "index": "src/index.html",
            "browser": "src/main.ts",
            "polyfills": [
              "zone.js"
            ],
            "tsConfig": "tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "stagging": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.stagging.ts"
                }
              ]
            },
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.development.ts",
                  "with": "src/environments/environment.ts"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "optimization": false,
              "extractLicenses": false,
              "sourceMap": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.development.ts"
                }
              ]
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "stagging": {
              "buildTarget": "angular-environment-demo:build:stagging"
            },
            "production": {
              "buildTarget": "angular-environment-demo:build:production"
            },
            "development": {
              "buildTarget": "angular-environment-demo:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "buildTarget": "angular-environment-demo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "polyfills": [
              "zone.js",
              "zone.js/testing"
            ],
            "tsConfig": "tsconfig.spec.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        }
      }
    }
  }
}

This file is the most important one when we want to make the best use of an environment file. To use the configuration from the environment.ts file, we need to serve the application with the following command: “ng serve --configuration=production”.

Note that you did not make any changes in the code, you have added only a new configuration and served the app using the new command. For example, if you are serving in production, you can use this command to serve in that environment. No changes in the code are required. It is common to have multiple environments used mostly for testing. When you need to accommodate a new environment, there are some steps to follow.

create a new environment file in the environment folder. For example, we can add environment.staging.ts.
Once this is created, do not forget to add values present in other environment files.

In the angular.json file, we need to add a new configuration under configuration.

The last part is still in the angular.json file. Now we need to add the configuration to serve the application using the respective environment file. These changes are done under "projects" -> "architect" -> "serve" -> "configurations"

We use the following command to serve the application using the settings found in the environment.stagging.ts file: ng serve --configuration=stagging. The screen that loads after serving is as follows.


Using environment files to use different APIs. Another powerful application of environment files is how easily, almost seamlessly it can be used to call different APIs for different environments.

Below are the steps.
Add the corresponding key-value pair in the environment object in all the environment files in your project, like below.
export const environment = {
    pageTitle: "Dinosaur",
    apiUrl: "https://dinosaur-facts-api.shultzlab.com/dinosaurs"
};

In your component.ts file, wherever required, you can call the web service in any method that you want.
For this example, we will be using the fetch method in a promise.
getInfo(){
  const myPromise = new Promise((resolve, reject) => {
    fetch(environment.apiUrl)
    .then((response) => response.json())
    .then((data) => {
      resolve(data)
    })
    .catch((error) => reject(error))
  });

  myPromise
  .then((result: any) => {
    const element = document.getElementById('txtResult');
    if (element) {
      element.innerHTML = JSON.stringify(result.slice(0, 5));
    }
    console.log(result.slice(0, 5));
  })
  .catch((error) => console.log(error))
  .finally(() => console.log('promise done'));
}

Notice that in the call, we are not passing any api. Instead, we are using the variable from the environment file.
At this point, the function is done and can be called when a button is clicked.
When we serve the application using: ng serve and click on the button, we get the following.

When we serve the application using ng serve --configuration=production, below is the output:

  • Note that there has been NO code change. We have only served the application using different serving configurations.
  • The same applies when you are deploying to an environment. Whether you are deploying your Angular app using Azure or something else, you are asked at some point the command to run the Angular application. Providing the correct serving configuration will use the required environment file and will display the corresponding information or call the desired API. No changes in code are required.

Conclusion
Environment files are very important and powerful. Maximizing their use will prevent you from doing manual changes when deploying in different stages.



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