Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE.eu :: Angular Content Projection: Reusability and Flexibility of the UI

clock February 1, 2024 08:13 by author Peter

The robust front-end framework Angular offers developers a number of tools to create dynamic and manageable user interfaces. Content projection is one such feature that greatly enhances UI flexibility and reusability. Through the dynamic injection of content into predetermined slots inside a component's template, content projection enables developers to design components that are both adaptable and reusable.


Comprehending Content Projection

A feature in Angular called content projection, or transclusion, allows content from a parent component to be inserted into a specific area of a child component. This method facilitates the creation of adaptable and adjustable user interfaces and encourages component reuse.

Content Projection's Advantages
Component Reusability: Content projection enables programmers to design components that may be applied to various areas of an application at different times. Content can be projected into designated slots to increase component versatility and adaptability to a range of use scenarios.
Simplified API: Rather than requiring intricate setups, components may expose a simplified API that accepts content as input. This improves code maintainability by making the components simpler for developers to use and comprehend.
Consistent Style and Layout: Content projection aids in preserving uniform styling and layout throughout an application's many sections. Components with specified slots can be designed by developers to guarantee that the content projection follows a consistent format.
Improved Concern Separation: Content projection promotes a distinct division of responsibilities between the parent and child components. Child components manage the content display, allowing parents to concentrate on business logic, thus fostering a modular and maintainable codebase.

Practical Use Case
Think of a basic card component that can show text, photos, or even bespoke components, among other kinds of information. We may construct a reusable card component that can adjust to various content kinds by using content projection.

card.component.ts

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

@Component({
  selector: 'app-card',
  standalone: true,
  imports: [],
  template: `
    <div class="card">
      <div class="card-header">
        <ng-content select="[card-header]"></ng-content>
      </div>
      <div class="card-body">
        <ng-content select="[card-body]"></ng-content>
      </div>
      <div class="card-footer">
        <ng-content select="[card-footer]"></ng-content>
      </div>
    </div>
  `,
  styles: [
    '.card { border: 1px solid #ddd; border-radius: 8px; overflow: hidden; margin: 16px; }',
    '.card-header, .card-footer { background-color: #f0f0f0; padding: 8px; }',
    '.card-body { padding: 16px; }',
  ],
})
export class CardComponent {}


In this example, the CardComponent defines three slots: card-header, card-body, and card-footer. The content projected into these slots will be rendered within the corresponding sections of the card.

app.component.ts
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { CardComponent } from './card/card.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, CardComponent],
  template: `
    <app-card>
      <div card-header>
        <h2>Angular is awesome</h2>
      </div>
      <div card-body>
        <p>Lets have a fun with it</p>
      </div>
      <div card-footer>
        <button>Read More</button>
      </div>
    </app-card>

    <app-card>
      <div card-header>
        <h2>Product Information</h2>
      </div>
      <div card-body>
        <img
          src="https://cdn-images-1.medium.com/v2/resize:fit:184/1*[email protected]"
          alt="Product Image"
          style="max-width: 100%"
        />
        <ul>
          <li>Feature 1</li>
          <li>Feature 2</li>
          <li>Feature 3</li>
        </ul>
      </div>
      <div card-footer>
        <button>Add to Cart</button>
      </div>
    </app-card>
  `,
})
export class AppComponent {}



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.



AngularJS Hosting Europe - HostForLIFE.eu :: Autofocus Directive in Angular

clock December 20, 2023 05:50 by author Peter

We will discover how to create a custom autofocus directive in an Angular application in this tutorial.


Required conditions
Basic familiarity with Angular 2 or later; installation of Node and NPM; Visual Studio Code; Bootstrap (Optional)

Make an Angular Project
The command to create an Angular project is as follows.
ng new angapp

Now install Bootstrap by using the following command,
npm install bootstrap --save

Now open the styles.css file and add Bootstrap file reference. To add a reference in the styles.css file add this line.
@import '~bootstrap/dist/css/bootstrap.min.css';


Create  Directive
Create  a new directive using the Angular CLI command
ng generate directive autofocus

Now open autofocus.directive.ts file and add following code
import { Directive, ElementRef, AfterViewInit } from '@angular/core';

@Directive({
  selector: '[Autofocus]'
})
export class AutofocusDirective implements AfterViewInit {
  constructor(private el: ElementRef) {}

  ngAfterViewInit() {
    this.el.nativeElement.focus();
  }
}


Now open app.component.html file and add the following code.
<div class="container" style="margin-top:10px;margin-bottom: 24px;">
  <div class="col-sm-12 btn btn-info">
    Autofocus Directive in Angular Application
  </div>
</div>
<div class="container">
  <input type="text" class="form-control" placeholder="Auto Focused Textbox" Autofocus />
</div>


Now open app.module.ts and following code
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AutofocusDirective } from './autofocus.directive';


@NgModule({
  declarations: [
    AppComponent, AutofocusDirective
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent],

})
export class AppModule { }


Now run the application using npm start and check the result.

We discovered how to make a personalized autofocus directive in an Angular application by reading this post.



AngularJS Hosting Europe - HostForLIFE.eu :: Angular Reverse String Pipe

clock December 15, 2023 06:50 by author Peter

We will discover how to build a pipe in an Angular application to reverse a string in this tutorial.


Required conditions
Basic familiarity with Angular 2 or later; installation of Node and NPM; Visual Studio Code; Bootstrap (Optional)

The command to create an Angular project is as follows.
ng new angapp

Now install Bootstrap by using the following command.
npm install bootstrap --save

Now open the styles.css file and add the Bootstrap file reference. To add a reference in the styles.css file, add this line.
@import '~bootstrap/dist/css/bootstrap.min.css';

Create a Reverse String Pipe
Now, create a custom pipe by using the following command.
ng generate pipe Reverse

Now open the Reverse.pipe.ts file and add the following code.
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'reverseString' })
export class Reverse implements PipeTransform {
  transform(value: string): string {
    if (!value) return value;
    return value.split('').reverse().join('');
  }
}


Now, create a new component by using the following command.
ng g c actionmenu

Now open searchlist.actionmenu.html file and add the following code.
<div class="container" style="margin-top:10px;margin-bottom: 24px;">
    <p>{{ 'Artificial Intelligence' | reverseString }}</p>
</div>


Now open app.component.html file and add the following code.
<div class="container" style="margin-top:10px;margin-bottom: 24px;">
  <div class="col-sm-12 btn btn-info">
    Reverse String Pipe in Angular
  </div>
</div>
<app-actionmenu></app-actionmenu>


Now run the application using npm start and check the result:

 



AngularJS Hosting Europe - HostForLIFE.eu :: How Can I Use Angular Application to Detect Event on Clicks Outside?

clock December 12, 2023 07:01 by author Peter

Overview
This post will teach us how to recognize an event in an Angular application when a user clicks outside of a component.


Required conditions
Basic familiarity with Visual Studio Code, Angular 2 or higher, Node and NPM installed, and Bootstrap

Make an Angular Project
The command to create an Angular project is as follows.

ng new angapp

Now install Bootstrap by using the following command,
npm install bootstrap --save

Now open the styles.css file and add Bootstrap file reference. To add a reference in the styles.css file add this line.
@import '~bootstrap/dist/css/bootstrap.min.css';

Now create a new component by using the following command,
ng g c actionmenu

Now open actionmenu.component.html file and add the following code.
<div class="sidebar {{show}} panel-group" clickOutside (clickOutside)="works()">
    <div class=" panel panel-default" >
        <div>
            <div class="panel-body">Panel Body</div>
            <div class="panel-footer">Panel Footer</div>
        </div>
    </div>
</div>


Now open actionmenu.component.ts file and add the following code.
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-actionmenu',
  templateUrl: './actionmenu.component.html',
  styleUrls: ['./actionmenu.component.css']
})
export class ActionmenuComponent {
  @Input() show: boolean=true;

  works() {
    this.show = !this.show;
  }
}


Now open actionmenu.component.css file and add the following code.
.sidebar {
    display: none;
}

.true {
    display: block;
}

.false {
    display: none;
}


Now open app.component.html file and add the following code.
<div class="container" style="margin-top:10px;margin-bottom: 24px;">
  <div class="col-sm-12 btn btn-info">
    How to detect clicks outside in Angular  Application
  </div>
</div>
<div class="container">
  <button type="button" class="btn btn-success" (click)="show = !show">Primary</button>
  <app-actionmenu [show]="show"></app-actionmenu>
</div>


Now open app.component.ts file and add the following code.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular App';
  show:boolean= false;
}


Now create a new directive by using the following command, and the following code in this directive.
ng g directive clickOutside

import { Directive, ElementRef, Input, Output, HostListener, EventEmitter } from '@angular/core';

@Directive({
    selector: '[clickOutside]'
})

export class ClickOutsideDirective {

    constructor(private elementRef: ElementRef) {}

    @Output() clickOutside: EventEmitter<any> = new EventEmitter();

    @HostListener('document: click', ['$event.target']) onMouseEnter(targetElement:any) {
        const clickInside = this.elementRef.nativeElement.contains(targetElement);
        if (!clickInside) {
            this.clickOutside.emit(null);
        }
    }
}

Now open app.module.ts and following code.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ActionmenuComponent } from './actionmenu/actionmenu.component';
import { ClickOutsideDirective } from './click-outside.directive';
@NgModule({
  declarations: [
    AppComponent,
    ActionmenuComponent,ClickOutsideDirective
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Now run the application using npm start and check the result.


Click outside anyplace in the component after clicking the button. This tutorial taught us how to detect events in the Compoent Angular application when a user clicks outside of any location.



Node.js Hosting Europe - HostForLIFE.eu :: TODO application with CQRS Design Pattern within Nest JS

clock December 4, 2023 08:53 by author Peter

A software design pattern called CQRS (Command Query Responsibility Segregation) divides up who is responsible for accessing and writing data in a system. The same set of components are frequently used in traditional design patterns for both reading and writing data. CQRS introduces two distinct models to suggest the division of these duties.

 

  • Command Model: The command model handles event triggering, data store updating, and command processing and validation.
  • Query Model: This model manages the processes involved in getting data out of the system.

The four major concepts of CQRS are listed below:

  • Command: Action or request to modify the system's status
  • Query: An occurrence or a request to obtain data from the system
  • Command Handler: An element in charge of processing commands and adjusting the system's state.
  • Query Handler: An element in charge of managing queries and getting information out of the system.

CQRS Offers Advantages like:

  • Scalability: Because the application supports several read and write data models, it can be scaled.
  • Flexibility: It permits the use of distinct data stores that are best suited for writing and reading processes.
  • Performance: There is room for improvement with this application.

This CQRS Model may be used with Nest JS; in this tutorial, we'll discover how to do it.

We'll use the creation and retrieval of a TODO application as an example using the CQRS paradigm.

Application for TODOs using CQRS pattern
You must use the command line to install nest cli if it is not already installed globally on your computer.
npm i -g @nestjs/cli

Create new Nest Js project if not created already using below command
nest new todo-application

Dependency Installation
Nest JS provides a package to implement CQRS, we need to install the package first using below command
npm install --save @nestjs/cqrs

Module Creation
Create new Module for our TODO application using command
nest generate module todo

Commands
Commands are used to change the application state, when a command is triggered, it is handled by corresponding command handler. Then handler will be responsible to process the operation. Every command will have command handler in order to process the command

Create new file inside todo module with name create-todo-command.ts and implement the below code
import { ICommand } from '@nestjs/cqrs';

export class CreateToDoCommand implements ICommand {
    constructor(
      public readonly title: string,
      public readonly description: string,
    ) {}
}

Command Handler
Create new file inside todo module with name create-todo-command-handler.ts  and implement the below code

import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { CreateToDoCommand } from './create-todo-command';

@CommandHandler(CreateToDoCommand)
export class CreateToDoHandler implements ICommandHandler<CreateToDoCommand> {
  async execute(command: CreateToDoCommand): Promise<void> {
    // Add Logic to do validation and business rule
    const { title, description } = command;

    // Use Repository to save directly or Create Factory to add business logic and save
  }
}


Query
Queries are used to retrieve the data from the application, when a query is requested, Query handler handles the requests and retrieves the data. Every query will have query handler

Create new file inside todo module with name get-todo-query.ts  and implement the below code
import {  IQuery } from '@nestjs/cqrs';

export class GetToDoQuery implements IQuery {
    constructor() {}
}

Query Handler
Create new file inside todo module with name get-todo-query-handler.ts  and implement the below code
import { IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { GetToDoQuery } from './get-todo-query';

@QueryHandler(GetToDoQuery)
export class GetToDoQueryHandler implements IQueryHandler<GetToDoQuery> {
  async execute(query: GetToDoQuery): Promise<any> {
    // Fetch data using repository or factory and return it
    // Sample Response
    return [
      { id: 1, title: 'Test', description: 'Reminder to complete daily activity' },
      { id: 2, title: 'Test 2', description: 'Reminder to complete daily activity2' },
    ];
  }
}


Module
In the todo.module.ts  file, import the CQRS module to use the command handlers and query handlers
import { Module } from '@nestjs/common';
import { CqrsModule } from '@nestjs/cqrs';
import { ToDoController } from './todo.controller';
import { CreateToDoHandler } from './create-todo-command-handler';
import { GetToDoQueryHandler } from './get-todo-query-handler';

@Module({
  imports: [CqrsModule],
  controllers: [ToDoController],
  providers: [CreateToDoHandler, GetToDoQueryHandler],
})
export class ToDoModule {}


Controller
Create todo.controller.ts  file to handle the API request and use command and query bus
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CommandBus, QueryBus } from '@nestjs/cqrs';
import { CreateToDoCommand } from './create-todo-command';
import { GetToDoQuery } from './get-todo-query';

@Controller('ToDo')
export class ToDoController {
  constructor(
    private readonly commandBus: CommandBus,
    private readonly queryBus: QueryBus,
  ) {}

  @Post()
  async createToDo(@Body() body: { title: string, description: string }): Promise<void> {
    const { title, description } = body;
    await this.commandBus.execute(new CreateToDoCommand(title, description));
  }

  @Get()
  async getToDo(): Promise<any[]> {
    return this.queryBus.execute(new GetToDoQuery());
  }
}

Pro Tips
You can create a separate folder for command and query to segregate the code and make it more readable. Also, here I just gave the basic high level demo, but in your application, you can create dto for command and query, and you can directly use that dto
Conclusion

In conclusion, while CQRS can provide advantages in terms of scalability and flexibility, it comes with increased complexity and potential challenges in terms of consistency and development overhead. It is important to carefully consider whether the benefits align with the specific requirements and goals of the application being developed.

HostForLIFE.eu Node.js 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. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.




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