Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE.eu :: Optimizing Templates for Angular

clock January 19, 2024 09:28 by author Peter

Immutable Objects: When using OnPush, it's beneficial to work with immutable objects. If you need to modify data, create a new object or array instead of modifying the existing one. This helps Angular recognize changes more efficiently.
this.data = [...this.data, newElement]; // Using the spread operator for arrays

Input Properties: Ensure that your component's input properties are used correctly. When an input property changes, Angular triggers change detection for components using the OnPush strategy. If you're working with complex data structures, consider using @Input setters to handle changes.
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-item',
  templateUrl: 'item.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ItemComponent {
  private _data: any;

  @Input()
  set data(value: any) {
    this._data = value;
    // handle changes if needed
  }

  get data(): any {
    return this._data;
  }
}


Event Handling: Be cautious with event handling. When using OnPush, events outside of Angular's knowledge (e.g., events from third-party libraries) may not trigger change detection automatically. Use ChangeDetectorRef to manually mark the component for check.
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  // Trigger change detection manually
  handleExternalEvent() {
    this.cdr.markForCheck();
  }
}


By using the OnPush change detection strategy and following these best practices, you can make your Angular application more efficient and responsive, especially in scenarios where components have a limited set of inputs or depend on immutable data.

2. Limit ngIf and ngFor in the Template

Limiting the use of ngIf and ngFor directives in your Angular templates is crucial for optimizing performance, as excessive use can lead to unnecessary rendering and affect the efficiency of change detection. Here are some best practices to follow:

  • Minimize ngIf and ngFor Nesting: Avoid deep nesting of ngIf and ngFor directives within your templates. The deeper the nesting, the more complex the change detection process becomes. Try to flatten your template structure when possible.
  • Filter Data Before Rendering: Instead of using ngFor to loop through all items and then applying conditions using ngIf, consider filtering your data in the component before rendering. This can reduce the number of elements in the template and improve rendering performance.

    <!-- Avoid -->
    <div *ngFor="let item of items" *ngIf="item.isValid">
      <!-- content -->
    </div>

    <!-- Prefer -->
    <div *ngFor="let item of validItems">
      <!-- content -->
    </div>


Use TrackBy with ngFor: When using ngFor, always provide a trackBy function to help Angular identify which items have changed. This can significantly improve the performance of rendering lists.
    <div *ngFor="let item of items; trackBy: trackByFn">
      <!-- content -->
    </div>


trackByFn(index, item) {
  return item.id; // Use a unique identifier
}


Avoid Excessive Use of Structural Directives: Be mindful of using too many structural directives (ngIf, ngFor, etc.) within a single template. Each structural directive introduces a potential change detection cycle, and having many of them can impact performance.

Lazy Load Components with ngIf: If you have complex or resource-intensive components, consider lazy-loading them using the ngIf directive. This way, the components will only be instantiated when they are needed.
<ng-container *ngIf="showComponent">
  <app-lazy-loaded-component></app-lazy-loaded-component>
</ng-container>


  • Paginate Large Lists: If dealing with large datasets, consider implementing pagination or virtual scrolling to load and render only the visible portion of the data. This can significantly improve the initial rendering time.
  • Profile and Optimize: Use Angular's built-in tools like Augury or browser developer tools to profile your application's performance. Identify components with heavy rendering and optimize accordingly.

3.  Lazy Loading Images
Lazy loading images is a technique that defers the loading of non-critical images until they are about to be displayed on the user's screen. This can significantly improve the initial page load time, especially for pages with a large number of images. Angular provides several ways to implement lazy loading of images. Here's a common approach:

Native Lazy Loading (HTML loading attribute): The HTML standard has introduced a loading attribute for the <img> element, which allows you to set the loading behavior of an image. The values can be "eager" (default), "lazy", or "auto". Setting it to "lazy" will enable lazy loading.
    <img src="image.jpg" alt="Description" loading="lazy">

The browser will then decide when to load the image based on its visibility in the viewport.

Angular Directives for Lazy Loading: You can use Angular directives for more control over lazy loading, especially if you need to perform custom actions when an image is loaded or when it enters the viewport.

a. Intersection Observer: Use the Intersection Observer API to detect when an element (such as an image) enters the viewport. Angular provides a directive named ng-lazyload-image that simplifies the integration with Intersection Observer.
npm install ng-lazyload-image

import { NgModule } from '@angular/core';
import { LazyLoadImageModule } from 'ng-lazyload-image';

@NgModule({
  imports: [LazyLoadImageModule],
  // ...
})
export class YourModule { }


<img [defaultImage]="'loading.gif'" [lazyLoad]="imagePath" alt="Description">

b. Custom Lazy Loading Directive: Alternatively, you can create a custom directive for lazy loading images. This approach provides more flexibility but requires a bit more code. You can use the Intersection Observer API or a library like lozad.js.
// lazy-load.directive.ts
import { Directive, ElementRef, Renderer2, OnInit } from '@angular/core';

@Directive({
  selector: '[appLazyLoad]'
})
export class LazyLoadDirective implements OnInit {

  constructor(private el: ElementRef, private renderer: Renderer2) { }

  ngOnInit() {
    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          this.loadImage();
          observer.unobserve(entry.target);
        }
      });
    });

    observer.observe(this.el.nativeElement);
  }

  private loadImage() {
    const imgSrc = this.el.nativeElement.getAttribute('data-src');
    if (imgSrc) {
      this.renderer.setAttribute(this.el.nativeElement, 'src', imgSrc);
    }
  }
}


<img [appLazyLoad]="imagePath" data-src="loading.gif" alt="Description">

4. ng-container
Use the <ng-container> element to group elements without introducing additional elements to the DOM. It is a lightweight container that doesn't render as an HTML element.
<ng-container *ngIf="condition">
  <!-- content -->
</ng-container>


5. Avoid Heavy Computation in Templates
Keep your templates simple and avoid heavy computations or complex logic. If necessary, perform such operations in the component class before rendering.
Move Logic to the Component
Use Pure Pipes Judiciously
Memoization
NgIf and NgFor Directives

6. Use Angular Pipes Efficiently
Be cautious with Angular pipes, especially those that involve heavy computations. Pipes can have an impact on performance, so use them judiciously. Consider memoization techniques if a pipe's output is deterministic and costly.
// component.ts
export class MyComponent {
  heavyComputationResult: any;

  ngOnInit() {
    // Perform heavy computation here
    this.heavyComputationResult = /* result */;
  }
}


<!-- component.html -->
<div>{{ heavyComputationResult | formatData }}</div>


7. ngZone Awareness

Be aware of NgZone and its impact on change detection. If you're performing operations outside of Angular (e.g., third-party libraries or asynchronous operations), you may need to use NgZone.run to ensure that change detection is triggered appropriately.

8. Production Build
Always build your application for production using AOT compilation. This helps in optimizing and minifying the code for better performance.
ng build --prod

By applying these optimization techniques, you can enhance the performance of your Angular templates and create a more responsive user experience.

Improving the performance of your Angular application requires optimizing Angular templates. To maximize Angular templates, consider the following advice and best practices:

1. Apply Change Detection using OnPush
Implementing Angular's OnPush change detection approach can greatly enhance your application's performance. Angular is instructed by the OnPush strategy to only check for changes when an event within the component is triggered or when the input attributes of the component change. Reduced change detection cycles may arise from this, improving overall performance. This is how OnPush is used:1.

Configure a Change Detection Method: Set ChangeDetectionStrategy as the changeDetection property in your component decorator.OnPush:

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

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent {
  // component logic
}



AngularJS Hosting Europe - HostForLIFE.eu :: Minification and Tree Shaking in Angular

clock January 15, 2024 07:26 by author Peter

Minification and tree shaking are two fundamental techniques used in Angular (and other web development frameworks) to streamline and optimize code for best performance. These methods assist in decreasing the size of your application, which is essential for improved user experience and quicker load times. Now let's examine each of these procedures in relation to Angular:

1. First off, what is minification?
Minification is the process of renaming variables to shorter names and eliminating characters from your code that aren't needed, including whitespace and comments. Your code files will download more quickly as a result of this smaller size. Typically, TypeScript is used to write Angular applications, and it is subsequently transpiled to JavaScript. The JavaScript code that results is subjected to the minification process.

This is how to make Angular's minification enabled.

A. Manufacturing Construct
To build your production application, you can use the build command provided by Angular CLI. The Angular CLI automatically applies minification when you build for production.

ng build --prod

This command generates a production-ready bundle with minified and optimized code.

B. The Terser Plugin
The Terser plugin, used for minification in Angular, provides with different configuration options. By including options in your angular.json file, you can alter the minification procedure.

"architect": {
  "build": {
    "options": {
      "optimization": true,
      "outputPath": "dist/my-app",
      "terserOptions": {
        "compress": {
          "pure_funcs": ["console.log"],
          "drop_console": true
        },
        "mangle": true
      }
    }
  }
}

The functions that are pure and can be safely removed are specified using the pure_funcs parameter in the example above. All console statements are eliminated using the drop_console option, and variable names are obscured by setting mangle to true.

C. Compiling Angular AOT (Ahead-of-Time)
There are two compilation modes for Angular applications: Just-In-Time (JIT) and AOT (Ahead-of-Time). For production builds, AOT compilation is recommended since it enables greater tree shaking and optimization. Smaller bundle sizes are the outcome of its compilation of Angular templates and components during the construction process.

In your tsconfig.json file, you can set AOT compilation to run automatically.

"angularCompilerOptions": {
  "fullTemplateTypeCheck": true,
  "strictInjectionParameters": true
}

2. What Is Shaking of Trees?
The practice of removing unused or dead code from your program is called tree shaking. It contributes to reducing the bundle size by removing any unnecessary modules or code.

A. Configuration of the Module
Make sure the arrangement of your Angular modules permits efficient tree shaking. Dependencies and boundaries between modules should be obvious. To make the process of removing useless code easier, stay away from needless inter-module dependencies.

B. Analysis of Static Data
Tree shaking is most effective when combined with static analysis, so stay away from runtime code or dynamic imports that make it difficult for the build tool to identify which portions of the code are being utilized.

C. Mode of Production
Like minification, production builds yield the best results from tree shaking. Tree shaking is enabled automatically by Angular CLI when you execute the production build with the --prod flag.

ng build --prod

2. What Is Shaking of Trees?
The practice of removing unused or dead code from your program is called tree shaking. It contributes to reducing the bundle size by removing any unnecessary modules or code.

A. Configuration of the Module

Make sure the arrangement of your Angular modules permits efficient tree shaking. Dependencies and boundaries between modules should be obvious. To make the process of removing useless code easier, stay away from needless inter-module dependencies.

B. Analysis of Static Data
Tree shaking is most effective when combined with static analysis, so stay away from runtime code or dynamic imports that make it difficult for the build tool to identify which portions of the code are being utilized.


C. Mode of Production
Like minification, production builds yield the best results from tree shaking. Tree shaking is enabled automatically by Angular CLI when you execute the production build with the --prod flag.

ng build --prod

D. Angular Dependency Injection
The dependency injection system in Angular occasionally causes issues with tree shaking. Steer clear of injecting components or services that aren't needed in a certain module. This guarantees that the services that are not utilized are excluded from the final package.

E. Renderer of Angular Ivy
Angular Ivy, the new rendering engine introduced in Angular 9, adds enhancements to tree shaking. Better static analysis capabilities enable more efficient removal of dead code during the build process.

Configuring Webpack (for Advanced Users):
You can alter the webpack configuration that the Angular CLI uses if you require further control over the build process. This creates a webpack.config.js file in your project and involves ejecting the webpack configuration. Utilize this file to adjust code splitting and optimization, among other build process components.

In order to remove the webpack setup:
ng eject

Remember that ejecting is final and that you will be in charge of keeping the webpack settings updated.

In summary

In summary, minification and tree shaking are combined to optimize Angular apps. Achieving optimal performance requires configuring Terser's settings, turning on AOT compilation, properly structuring modules, and being aware of the limitations of tree shaking. Make sure the optimizations don't affect your application's functioning by conducting extensive testing.



AngularJS Hosting Europe - HostForLIFE.eu :: How To Configure AngularJS Environment Variables?

clock January 10, 2024 07:07 by author Peter

Setting environment variables in an AngularJS application happens at the configuration stage; this usually takes place in a separate file containing the configuration data. This is an illustration of how to set environment variables in an AngularJS application:

First Step
To save the environment variables, create a file in the root directory of your application, say config.js.

Step Two
Use the following code to define the environment variables in the file:

"use strict";
 angular.module('config', [])
.constant('ENV', {name:'development',tokenURL:'http://localhost:62511/token',apiURL:'http://localhost:62511/api',biUrl:'http://localhost:4200/',backgroundimage:'../images/backgroundimage.jpg',logo:'images/ogo.png'});


Step 3

Include the config.js file in your HTML file, just like any other JavaScript file:
<script src="scripts/index.config.js"></script>

Step 4

Inject the env constant in your AngularJS controllers, services, or directives to access the environment variables,

angular.module("myApp").controller("MyController", function($scope, env) {
    console.log(env.apiUrl);
    console.log(env.debugEnabled);
});
development: {
        options: {
            dest: '<%= yeoman.app %>/scripts/config.js'
        },
        constants: {
            ENV: {
                name: 'development',
                tokenURL: "http://localhost:62511/token",
                apiURL: "http://localhost:62511/api",
                biUrl: "http://localhost:4200/",
                backgroundimage: "../images/backgroundimage.jpg",
                logo: "images/logo.png",
            }
        }
    },
    qa: {
        options: {
            dest: '<%= yeoman.dist %>/scripts/config.js'
        },
        constants: {
            ENV: {
                name: 'qa',
                tokenURL: "https://qa.hostforlife.eu/token",
                apiURL: "https://qa.
hostforlife.eu/api",
                biUrl: "https://qa-dashboard.
hostforlife.eut/",
                backgroundimage: "../images/backgroundimage.jpg",
                logo: "images/logo.png",
            }
        }
    },

Grunt command to run the Application,

grunt build --qa



SQL Server Hosting - HostForLIFE :: Recognizing SQL's One-Way HASHBYTE Characteristic

clock January 8, 2024 07:14 by author Peter

Hashing functions in SQL Server work as cryptographic instruments to produce distinct fixed-size hash values from input data. This compilation features a variety of hash algorithms, all of which are intended to provide unique hash values for a given input string.

  • Once-commonly used MD2, MD4, and MD5 algorithms produce hashes with a length of 128 bits. But now since they have flaws, they are considered insecure.
  • SHA1 and SHA (Secure Hash Algorithm): These algorithms, which are members of the SHA family, generate hash values with different bit lengths. Even while SHA-1 was once in use, its flaws have made it obsolete in favor of safer substitutes.
  • SHA2_256 and SHA2_512: These members of the SHA-2 family provide hash values of 256 and 512 bits, respectively, and are presently regarded as secure in the context of cryptography.

1. Message Digest Algorithm 2, or MD2
A cryptographic hash function called MD2 generates a hash value of 128 bits. Although this older method is renowned for being straightforward, it has flaws and is no longer advised for use in situations where security is a concern.

As an illustration
SELECT HASHBYTES('MD2', 'Hello, World!') AS [MD2 HashValue];

2. MD4 (Message Digest Algorithm 4)
MD4 is a cryptographic hash function designed to produce a 128-bit hash value. It's also considered obsolete and insecure due to vulnerabilities.

Example:
SELECT HASHBYTES('MD4', 'Hello, World!') AS [MD4 HashValue];

3. Message Digest Algorithm 5, or MD5
A popular cryptographic hash algorithm that produces a 128-bit hash result is MD5. However, it is no longer regarded as secure for essential applications because of weaknesses and collision attacks.

As an illustration
SELECT HASHBYTES('MD5', 'Hello, World!') AS [MD5 HashValue];


4. SHA (Secure Hash Algorithm)
The SHA family of cryptographic hash algorithms consists of SHA-1, SHA-2, SHA-3, and SHA-0 (deprecated). More secure versions of SHA-0 and SHA-1 are gradually replacing the deemed weaker ones.

Example
SELECT HASHBYTES('SHA', 'Hello, World!') AS [SHA HashValue];

5. SHA1 (Secure Hash Algorithm 1)
A 160-bit hash value is generated by SHA-1. Although it was widely used, vulnerabilities have caused it to be deprecated. Collision attacks were successful because of its flaws.

Example:

SELECT HASHBYTES('SHA1', 'Hello, World!') AS [SHA1 HashValue];

6. SHA2_256 (Secure Hash Algorithm 2 - 256 bit):
SHA-256 is part of the SHA-2 family and generates a 256-bit hash value. It's currently considered secure and widely used for various cryptographic applications.

Example

SELECT HASHBYTES('SHA2_256', 'Hello, World!') AS [SHA2_256 HashValue];

7. SHA2_512 (Secure Hash Algorithm 2 - 512 bit)
SHA-512, another member of the SHA-2 family, produces a 512-bit hash value. It's a more secure and larger variant of SHA-256.

Example

SELECT HASHBYTES('SHA2_512', 'Hello, World!') AS [SHA2_512 HashValue];

A variety of hash algorithms are available in SQL Server, and each one creates distinct hash values from input strings. Although SHA-1 and MD5 were once widely used, their flaws now warn against using them. As a safe substitute, the SHA-2 family, which includes SHA2_256 and SHA2_512, is used instead.

Selecting an algorithm that strikes a balance between security requirements and performance is crucial. Database professionals can strengthen security protocols and data integrity in SQL Server configurations by understanding these hashing subtleties.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu 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.

 



AngularJS Hosting Europe - HostForLIFE.eu :: Concat Operator in RxJS Library

clock January 3, 2024 06:51 by author Peter

The concat operator is used in RxJS (Reactive Extensions for JavaScript) to concatenate multiple observables together, sequentially, in the order that they are supplied. It makes ensuring that emissions from observables are processed sequentially and that they are subscribed to.


Set up RxJS

You can use npm to install RxJS if you haven't previously.

npm install rxjs

Import Concat and Any Other Essential Programs
To create observables, import the concat operator along with any additional functions or operators that you require. One way to build observables with values would be to utilize of.

import { concat, of } from 'rxjs';

Basic Syntax of RxJS
import { concat } from 'rxjs';
const resultObservable = concat(observable1, observable2, observable3, ...);

The concat function takes multiple observables as arguments, and it returns a new observable (resultObservable) that represents the concatenation of these observables.

Sequence of Action

  • In the order that they are passed to concat, observables are subscribed to.
  • Each observable's values are processed one after the other.

Awaiting Finalization

  • Concat waits for every observable to finish before proceeding to the following one.
  • Subsequent observables won't be subscribed to if an observable never completes, meaning it keeps emitting values forever.

Example
import { concat, of } from 'rxjs';

const observable1 = of(1, 2, 3);
const observable2 = of('A', 'B', 'C');

const resultObservable = concat(observable1, observable2);

resultObservable.subscribe(value => console.log(value));

Output
1 2 3 A B C

In this example, observable1 emits values 1, 2, and 3, and then observable2 emits values 'A', 'B', and 'C'. The concat operator ensures that the values are emitted in the specified order.

Use Cases

concat is useful when you want to ensure a sequential execution of observables.
It's commonly used when dealing with observables that represent asynchronous operations, and you want to perform these operations one after the other.

Error Handling
If any observable in the sequence throws an error, concat will stop processing the sequence, and the error will be propagated to the subscriber.

The concat operator in RxJS is a powerful tool for managing the sequential execution of observables, providing a clear order of operations and waiting for each observable to complete before moving on to the next one.



About HostForLIFE.eu

HostForLIFE.eu 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in