Full Trust European Hosting

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

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.



AngularJS Hosting Europe - HostForLIFE :: Get Browser Type and Version Using Angular and Bootstrap

clock February 20, 2024 06:04 by author Peter

This article explains how to retrieve the browser name and version from the Angular application. In certain cases, you may also need to obtain the browser name in Angular, depending on your requirements. If the Angular application is open on Internet Explorer Legacy, Edge, Firefox, Chrome, Safari, Opera, or another browser, we can quickly identify it. This article walks us through the process of adding a reusable method to an Angular application and demonstrates how to quickly identify the browser and version.


Note: Before beginning this session, please read my earlier essay (linked below) about Angular applications.

D:\EmployeeManagement\CallWebAPIAngular> ng g s services/detect-browser

Then you can service and its related files are shown below
PS D:\EmployeeManagement\CallWebAPIAngular> ng g s services/detect-browser
CREATE src/app/services/detect-browser.service.spec.ts (393 bytes)
CREATE src/app/services/detect-browser.service.ts (142 bytes)


Step 2. Configure browser name with version detection method
After creating the DetectBrowserService, add the getBrowserNameAndVersion() method to return an object with name and version keys. This method will fetch the User-Agent strings on the browser in which the Angular application is loaded.

Open the ~app\services\detect-browser.service.ts file and add as shown below.
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class DetectBrowserService {
  constructor() { }
  getBrowserNameAndVersion() {
    var ua = navigator.userAgent,
        tem,
        M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];

    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return { name: 'IE', version: (tem[1] || '') };
    }
    if (M[1] === 'Chrome') {
        tem = ua.match(/\bEdg\/(\d+)/);
        if (tem != null) {
            return { name: 'Edge(Chromium)', version: tem[1] };
        }
        tem = ua.match(/\bOPR\/(\d+)/);
        if (tem != null) {
            return { name: 'Opera', version: tem[1] };
        }
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) {
        M.splice(1, 1, tem[1]);
    }
    return {
      name: M[0],
      version: M[1]
    };
  }
}


Here, we detect the name and version of the browser by creating a new service with a common method. The getBrowserNameAndVersion method returns an object with name and version keys. This method is fetching the User-Agent string that provides the browser information.

Step 3. Detect browser name with version
Now, we will import the DetectBrowserService in the AppComponent‘s constructor function. The service instance method named getBrowserNameAndVersion() will assign the name and version object to the browserNameAndVersion variable.

Open the app.component.ts file and add as shown below

import { Component } from '@angular/core';
import { DetectBrowserService } from './services/detect-browser.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Display Browser Name & Version';

  public requiredVersion = 98;
  public isBrowserOutdated: boolean | undefined;
  public browserVersion = '';
  browserNameAndVersion: any;

  constructor(
    detectBrowserService: DetectBrowserService
  ) {
    this.browserNameAndVersion = detectBrowserService.getBrowserNameAndVersion();
    this.browserVersion = this.browserNameAndVersion.version;
    if (parseFloat(this.browserNameAndVersion.version) < this.requiredVersion) {
      this.isBrowserOutdated = true;
    }
  }
}

Here we configure for displaying browser name and version along with browser up-to-date or not.

this.browserNameAndVersion = detectBrowserService.getBrowserNameAndVersion();
this.browserVersion = this.browserNameAndVersion.version;
if (parseFloat(this.browserNameAndVersion.version) < this.requiredVersion) {
  this.isBrowserOutdated = true;
}


Step 4. HTML template to show browser name with version
Update the HTML template of AppComponent to display the browser name and version. Open the app.component.html file and update it as shown below:

<div class="card bg-danger text-white">
  <div class="card-body text-center">
    <h1>{{ title }}</h1>
  </div>
  <table class="table table-striped mt-5">
    <thead>
    </thead>
    <tbody>
      <tr>
        <td><h4>Browser Name: {{ browserNameAndVersion.name | titlecase }}</h4></td>
        <td><h4>Current Browser Version: {{ browserNameAndVersion.version | titlecase }}</h4></td>
        <td><h4>Required Version: {{ requiredVersion }}</h4></td>
      </tr>
    </tbody>
  </table>
</div>

<div class="toast show" style="position: fixed; top: 60%; left: 50%; width: 30em; height: 17em; margin-top: -9em; margin-left: -15em; border: 1px solid #ccc; background-color: #f3f3f3; color: red; font-weight: 900; font-size: larger;">
  <div class="toast-header">
    Angular Detect Browser Name and Version
    <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
  </div>
  <div class="toast-body">
    <div class="base-block" *ngIf="isBrowserOutdated">
      <h1>Oops</h1>
      <h3>Browser is outdated</h3>
      <h5>
        Your {{ browserNameAndVersion.name }} browser is outdated ({{ browserNameAndVersion.version }}) as less than required Version
        ({{ requiredVersion }}) and no longer supported, please update your browser.
      </h5>
    </div>

    <div class="base-block" *ngIf="!isBrowserOutdated">
      <h1>Cheers!</h1>
      <h3>Browser is up to date</h3>
      <h5>
        Your {{ browserNameAndVersion.name }} browser is updated ({{ browserNameAndVersion.version }}).
      </h5>
    </div>
  </div>
</div>


Use the interpolation to display the browser name and version with the help of the interpolation. An Interpolation is defined using the double curly braces that permit the user to bind a value to a UI element. Also, we will use the angular pipe to transform the value in the title case.

<td>
  <h4>Browser Name: {{ browserNameAndVersion.name | titlecase }}</h4>
</td>
<td>
  <h4>Current Browser Version: {{ browserNameAndVersion.version | titlecase }}</h4>
</td>
<td>
  <h4>Required Version: {{ requiredVersion }}</h4>
</td>

Check browser is up-to-date or not based on some condition using the *ngIf directive.
<div class="toast-body">
  <div class="base-block" *ngIf="isBrowserOutdated">
    <h1>Oops</h1>
    <h3>Browser is outdated</h3>
    <h5>
      Your {{ browserNameAndVersion.name }} browser is outdated ({{ browserNameAndVersion.version }}) as less than required Version
      ({{ requiredVersion }}) and no longer supported, please update your browser.
    </h5>
  </div>

  <div class="base-block" *ngIf="!isBrowserOutdated">
    <h1>Cheers!</h1>
    <h3>Browser is up to date</h3>
    <h5>
      Your {{ browserNameAndVersion.name }} browser is updated ({{ browserNameAndVersion.version }}).
    </h5>
  </div>
</div>


Step 5. Add Bootstrap to make the page responsive
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Title Service Example</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>


Output

Finally, run the application by executing the ng serve command in the terminal window. It opens the application at the following URL: http://localhost:4200/
Checking Chrome Browser is up to date i.e. based required Version

Checking whether Chrome Browser is up to date or not i.e. based on the Required Version

Checking whether another Browser is up to date or not i.e. based on the Required Version

Why is it necessary to set up the browser detection procedure?
To let users know that their current browser or version isn't compatible with correctly loading the application, we need to identify the name and version of their browser. They can then use the newest browsers that are out there. Modern Javascript and CSS principles are supported by a wide range of web browsers accessible today, all of which are completely compatible with the most recent version of WebKit. In this situation, we must identify the browser's name and version in order to let users know that their current browser or a different one isn't compatible with correctly loading the program and that they can upgrade to the newest version.



AngularJS Hosting Europe - HostForLIFE :: Which Angular Modifiers Are Important?

clock January 22, 2024 07:12 by author Peter

In Angular, key modifiers are special keys that you can use in combination with other keys to capture specific keyboard events. These modifiers help you distinguish between different key combinations and provide more flexibility in handling user input.


Key modifiers in Angular
Here are some key modifiers commonly used in Angular.
$event: This is a special variable that you can use to access the native event object in your event handler. For example.

<input (keyup)="onKeyUp($event)">

In the component:

onKeyUp(event: KeyboardEvent): void {
    // Access event properties, such as event.keyCode, event.key, etc.
}

(keyup.enter) and (keyup.esc): These are examples of key modifiers for specific keys. They allow you to handle events triggered by the Enter key or the Escape key.

<input (keyup.enter)="onEnterKey()" (keyup.esc)="onEscapeKey()">

In the component
onEnterKey(): void {
    // Handle Enter key press
}

onEscapeKey(): void {
    // Handle Escape key press
}


(keydown.space): Similar to (keyup.enter), this allows you to handle events triggered by the Space key.
<button (keydown.space)="onSpaceKey()">Click me with Space</button>

In the component
onSpaceKey(): void {
    // Handle Space key press
}

(keyup.shift): You can use this to handle events triggered when the Shift key is released.
<input (keyup.shift)="onShiftKeyUp()">

In the component
onShiftKeyUp(): void {
    // Handle Shift key release
}


(keydown.ctrl) and (keydown.meta): These modifiers allow you to handle events when the Ctrl (Control) key or the Meta key (Command key on Mac) is pressed.
<input (keydown.ctrl)="onCtrlKeyDown()" (keydown.meta)="onMetaKeyDown()">

In the component:
onCtrlKeyDown(): void {
    // Handle Ctrl key press
}

onMetaKeyDown(): void {
    // Handle Meta key press
}

With the help of these key modifiers, it is possible to record particular key-related events and carry out actions in response to user input. They make your Angular applications more interactive by enabling you to react to keyboard inputs in a more sophisticated



AngularJS Hosting Europe - HostForLIFE :: Observable Management Using NgIf and Async Pipe

clock January 18, 2024 08:01 by author Peter

When the component loads, Angular's async pipe subscribes to an Observable or Promise and returns the value that was last emitted. Every time a new value is emitted, the async pipe designates the component that needs to be examined for modifications. When the component is destroyed, it will automatically unsubscribe. Additionally, the async pipe immediately unsubscribes from the current Observable or Promise and subscribes to a new one when the reference of an expression changes.

An illustration of an observable-based async pipe


Our basic component subscribes to the currentTime$ observable via the async pipe. Every time the observable emits a new value, the value that is displayed is automatically updated.

import { Component } from '@angular/core';
import { Observable, interval } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `
    <h1>Async Pipe Example</h1>
    <p>Current time: {{ currentTime$ | async }}</p>
  `
})
export class AppComponent {
  currentTime$: Observable<Date>;

  constructor() {
    this.currentTime$ = interval(1000).pipe(
      map(() => new Date())
    );
  }
}

The currentTime$ observable is created using the interval an operator from RxJS, which emits a sequential number every 1 second.
We then use the map operator to transform the emitted number into a Date object representing the current time.
In the template, we use the async pipe to directly bind the value of currentTime$ to the {{ currentTime$ | async }} expression, which will automatically handle subscribing and unsubscribing from the observable.
This way, the template will always display the current time, updating every second as new values are emitted by the observable.

When should I use Async Pipe with ngIf?
When you wish to conditionally show content based on the outcome of an asynchronous operation or the existence of data from an asynchronous source, you can use the ngIf directive and async pipe.

Here are some typical situations in which ngIf and async pipe might be used.

  • Data Loading: ngIf with async pipe can be used to display a loading message or spinner until the data is loaded and ready to be displayed when retrieving data from an API or carrying out an asynchronous action.
  • Authentication and Authorization: ngIf with async pipe can conditionally show or hide specific UI components based on the user's permissions and access privileges when implementing authentication and authorization in an application.
  • Conditional Rendering: ngIf with async pipe is used to conditionally render different sections of a template based on the status of the asynchronous operation if you have conditional logic in your template that depends on the outcome of an asynchronous operation.

Example of ngIf and Async Pipe

Here, we have an AppComponent that declares an Observables called data$. The data$ observable simulates an asynchronous data retrieval using the of operator and delay operator from RxJS.
import { Component } from '@angular/core';
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
>
@Component({
  selector: 'app-root',
  template: `
    <div *ngIf="data$ | async as data; else loading">
      <h1>Data is loaded:</h1>
      <p>{{ data }}</p>
    </div>

    <ng-template #loading>
      <h1>Loading data...</h1>
    </ng-template>
  `,
})
export class AppComponent {
  data$: Observable<string>;

  constructor() {
    // Simulating an asynchronous data retrieval
    this.data$ = of('Hello, world!').pipe(delay(2000));
  }
}


TypeScript

  • We conditionally display content in the template based on the completion of the data$ observable by using the ngIf directive.
  • Before assigning the value to the data variable using the as syntax, the data$ observable must be subscribed to and retrieved using the async pipe.
  • The loaded data is shown inside the ngIf block, and a loading message is shown inside the ng-template with the #loading reference.
  • The template will show the value that is emitted by the data$ observable. The loading notice will appear until then.
  • The async pipe handles subscription and automatically updates the UI when the observable emits new values or when it completes.

By using ngIfwith asyncpipe, you can simplify your code and let Angular handle the management of subscriptions and automated changes of the view when the asynchronous operation finishes or emits new values. In general, you can write more succinct and clear code for managing asynchronous operations and conditional rendering in Angular applications by utilizing ngIf with async pipe.



AngularJS Hosting Europe - HostForLIFE :: Using Angular CLI 17.0.6, Node: 20.0.1, and npm 10.2.3 on Windows, Create Your First Angular

clock December 19, 2023 06:08 by author Peter

On November 6, 2023, Angular 17 was launched, and I wanted to create my first application with it. These instructions will help you create your first Angular 17 application. With the exception of a few advanced capabilities that must be enabled, this is essentially the same if you have expertise with earlier Angular versions. In addition to a fresh style, Angular 17 introduces several new capabilities for developers and performance. Additionally, Angular17 has well-managed documentation.

Developing an Angular 17 Application
Required conditions

Install the most recent LTS version of NODE JS. I've utilized 20.10.0. Installing and downloading this can be done at https://nodejs.org/en.
During installation, make sure to tick the set Path in the Environment Variables option.

Installing Angular CLI is a required that will be done concurrently with node js installation.
After the installation is complete, use CMD to verify the installed version of the node.

Enter "node -v" in the command window. This screen grab below displays the version that I have installed.

After Node js has been successfully installed, Typescript needs to be installed. Try using the admin version of cmd. Given that folder rights were restricted, I knew I had to take this action. I've included some instructions below in case you're operating through a proxy.

CMD "npm install –g typescript" should be run.

if any of the following mistakes happen. CERT_IN_CHAIN_SELF SIGNED.

I got around the certificate, which is the above error, with this cmd. "npm config set strict-ssl false" Strict SSL configuration will now be set to false. If the installation goes well, it will seem like the screen below, which indicates that the installation was successful.

Run the command "npm install -g @angular/cli@latest" as shown above the screen. It does say about funding which is to ask for funds.
Some of these packages installed are probably asking for funds. (optional)

You can check the version installed using the command "ng version"

Now that the prerequisites have been met, use the command "ng new {APPName}" to begin building a new Angular17 application. The CLI will inquire about the type of styling you want to use and whether you need to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering) when you create a new application.

When user interaction with the backend is required, server-side rendering is employed.

To launch the ng serve –o application, use this command. Your browser will launch it at http://localhost:4200/.


Thank you, and Hopefully, this article helped you get started with creating an angular 17 application.



AngularJS Hosting Europe - HostForLIFE :: ng-container, ng-template, and ng-content

clock August 25, 2023 08:22 by author Peter

ng-container
By enabling you to apply Angular directives without including additional items in the DOM (Document Object Model), the ng-container functions as a kind of transparent container. It is frequently employed when you wish to structure or conditionally include elements in your template.


As an illustration, consider creating a product page. If the product is in stock, you want to display the product details; otherwise, you want to display a notification stating the product is unavailable.

<ng-container *ngIf="productAvailable; else outOfStockTemplate">
  <div>Product Name: {{ productName }}</div>
  <div>Price: {{ productPrice }}</div>
</ng-container>

<ng-template #outOfStockTemplate>
  <div>This product is currently out of stock.</div>
</ng-template>

ng-template
The ng-template is like a template blueprint that doesn't get displayed immediately. It's used to define sections of your template that can be reused and conditionally rendered using structural directives.

Example: Let's say you're creating a list of blog posts. You want to show different styles for featured posts and regular posts.
<ul>
  <ng-container *ngFor="let post of posts">
    <ng-container *ngTemplateOutlet="post.featured ? featuredTemplate : regularTemplate; context: { post: post }"></ng-container>
  </ng-container>
</ul>

<ng-template #featuredTemplate let-post>
  <li class="featured">{{ post.title }}</li>
</ng-template>

<ng-template #regularTemplate let-post>
  <li>{{ post.title }}</li>
</ng-template>


ng-content
The ng-content is used to allow external content to be included within the template of your component. It's ideal for making more adaptable components that can be used in a variety of situations. Consider designing a card component that can display a variety of content.
<div class="card">
  <div class="card-header">
    <ng-content select=".card-title"></ng-content>
  </div>
  <div class="card-content">
    <ng-content></ng-content>
  </div>
  <div class="card-footer">
    <ng-content select=".card-actions"></ng-content>
  </div>
</div>


Now, when you use this component, you can provide custom content for each section:
<app-card>
  <div class="card-title">Card Title</div>
  <p>This is the content of the card.</p>
  <div class="card-actions">
    <button>Edit</button>
    <button>Delete</button>
  </div>
</app-card>


By combining these concepts, you can create components that are more dynamic and adaptable. ng-container, ng-template, and ng-content help you organize and structure your templates in a way that makes your code more readable and maintainable.



AngularJS Hosting Europe - HostForLIFE :: Important RxJS Operators

clock August 21, 2023 08:54 by author Peter

RxJS (Reactive Extensions for JavaScript) is a sophisticated tool used in Angular applications for handling asynchronous and event-based programming with observables. RxJS provides a diverse set of operators for manipulating, transforming, combining, and managing observables in a flexible and functional manner. These operators facilitate reactively working with data streams and asynchronous processes.


Here's a rundown of some of the most common RxJS operators and how they can be utilized in Angular:
map

The map operator is used to transform observable values into new ones. This is frequently used to do data transformations.

import { map } from 'rxjs/operators';

observable.pipe(
  map(data => data * 2)
).subscribe(result => console.log(result));


filter
The filter operator is used to remove values from an observable depending on a criterion.
import { filter } from 'rxjs/operators';

observable.pipe(
  filter(data => data > 5)
).subscribe(result => console.log(result));


mergeMap (flatMap)
The mergeMap operator is used to merge multiple observables into a single observable by applying a function to each emitted value and flattening the resulting observables.
import { mergeMap } from 'rxjs/operators';

observable.pipe(
  mergeMap(data => anotherObservable(data))
).subscribe(result => console.log(result));


switchMap
The switchMap the operator is similar to mergeMap, but it switches to a new inner observable whenever a new value is emitted from the source observable, canceling the previous inner observable.
import { switchMap } from 'rxjs/operators';

observable.pipe(
  switchMap(data => anotherObservable(data))
).subscribe(result => console.log(result));


debounceTime
The debounceTime operator delays emitted values for a specified amount of time and only emits the last value within that time frame.
import { debounceTime } from 'rxjs/operators';
inputObservable.pipe(
  debounceTime(300)
).subscribe(value => console.log(value));

combineLatest
The combineLatest operator combines the latest values from multiple observables whenever any of the observables emit a new value.
import { combineLatest } from 'rxjs/operators';

combineLatest(observable1, observable2).subscribe(([value1, value2]) => {
  console.log(value1, value2);
});

catchError
The catchError operator is used to handle errors emitted by an observable by providing an alternative observable or value.
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';

observable.pipe(
  catchError(error => of('An error occurred: ' + error))
).subscribe(result => console.log(result));


These are just a few examples of the many RxJS operators available. Using RxJS operators effectively can help you manage complex asynchronous workflows, handle data transformations, and create more responsive and reactive Angular applications.

Happy Learning :)



AngularJS Hosting Europe - HostForLIFE :: Improving Performance through Angular Change Detection Techniques

clock May 19, 2023 08:27 by author Peter

Change detection is an integral component of Angular that ensures the user interface is in alignment with the state of the application. ChangeDetectionStrategy is Angular's default detection strategy.Standard, which examines for modifications to all components and their templates on each JavaScript event or timer tick.


Nevertheless, this default strategy may result in superfluous and expensive change detection cycles, particularly in large-scale applications. Alternative strategies, such as OnPush, enter into play at this point. The OnPush strategy optimizes change detection by focusing solely on a component's inputs and references.

Using the OnPush strategy, Angular determines if a component's input properties have changed. If the input values remain the same, Angular assumes that the component's state hasn't changed and skips its change detection entirely. This optimization can significantly improve the performance of your Angular application, especially when used strategically.

import { Component, Input, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-user',
  template: `
    <h2>{{ user.name }}</h2>
    <p>{{ user.email }}</p>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserComponent {
  @Input() user: User;
}

In this example, the UserComponent has the OnPush change detection strategy defined. By doing so, we instruct Angular to only perform change detection if the user input property changes.

When using the OnPush strategy, it is essential to ensure that the user input property is immutable. If you update the user object's properties, Angular won't detect the changes, as it relies on reference comparison.

To optimize performance further, you can utilize the ChangeDetectorRef to manually trigger change detection when necessary:

import { Component, Input, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-user',
  template: `
    <h2>{{ user.name }}</h2>
    <p>{{ user.email }}</p>
    <button (click)="updateUser()">Update</button>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserComponent {
  @Input() user: User;

  constructor(private cdr: ChangeDetectorRef) {}

  updateUser() {
    // Update the user object
    this.cdr.markForCheck(); // Trigger change detection
  }
}


In the above example, we inject the ChangeDetectorRef and call its markForCheck() method to manually trigger change detection when the user clicks the "Update" button.

By understanding and utilizing Angular's change detection strategies, especially the OnPush strategy, you can significantly enhance the performance of your Angular applications. By minimizing unnecessary change detection cycles, your app will run more efficiently and provide a smoother user experience.

Remember to carefully analyze your application's requirements and components' state before choosing a change detection strategy. Applying the OnPush strategy to components that rarely change or have immutable input properties can lead to noticeable performance improvements.



AngularJS Hosting Europe - HostForLIFE :: Interceptors In Angular Along With Benefits

clock April 10, 2023 08:33 by author Peter

In Angular, an interceptor is a middleware that intercepts HTTP requests and responses. Interceptors are used to manipulate or transform HTTP requests and responses globally. This means you can modify HTTP requests and responses in one place and affect all the requests and responses that go through that place.

 

Ininterceptors In Angular
Interceptors are a powerful tool in Angular as they can be used for a wide variety of tasks, such as,
    Adding authorization headers to requests
    Logging requests and responses
    Adding or removing parameters from requests
    Transforming response data

How to implement an interceptor in Angular?
To implement an interceptor in Angular, you need to create a class that implements the HttpInterceptor interface. The HttpInterceptor interface has two methods to implement: intercept() and, optionally, handleError().

So let's start. Here's an example of an interceptor that adds an authorization header to every HTTP request,
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
        // Get the access token from your authentication service
        const accessToken = this.authService.getAccessToken();
        // Clone the request and add the authorization header
        const authRequest = request.clone({
            headers: request.headers.set('Authorization', `Bearer ${accessToken}`)
        });
        // Pass the cloned request to the next handler in the chain
        return next.handle(authRequest);
    }
}


In this example, the AuthInterceptor class implements the HttpInterceptor interface and overrides the intercept() method. In the intercept() method, we get the access token from our authentication service and clone the incoming request, adding an authorization header. We then pass the cloned request to the next handler in the chain using the next.handle() method.

To use this interceptor, register it with the Angular HTTP client. You can do this by providing it in the provider's array of your AppModule,
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AuthInterceptor } from './auth.interceptor';

@NgModule({
    imports: [BrowserModule, HttpClientModule],
    providers: [{
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true
    }]
})
export class AppModule {}


In this example, we import the HttpClientModule and our AuthInterceptor class. We then provide our interceptor in the provider's array using the HTTP_INTERCEPTORS token. The multi-option is set to true, which means that this interceptor is added to the existing array of HTTP interceptors rather than replacing it.
Benefits of using interceptors in Angular

    Interceptors allow the manipulation of HTTP requests and responses globally, making it easy to implement cross-cutting concerns such as authentication and error handling.
    Interceptors can reduce code duplication by providing a centralized place to modify requests and responses.
    Interceptors can be easily added or removed, making it easy to change the behavior of your application without having to modify every HTTP request and response.

Summary
Interceptors are a powerful Angular tool that allows you to manipulate HTTP requests and responses globally. They can be used for various tasks and provide a centralized place to modify requests and responses. By using interceptors, you can reduce code duplication and easily add or remove functionality from your application.



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