Friday, July 29, 2022

Directives

 Angular Directives

   Angular directives are used to extend the HTML's power by giving it new syntax.

   Directives can Extend, change or Modify the Behavior of the DOM Elements.

  



Types of Directives

  1. Structural Directives

  2. Attribute Directives

  3. Component Directives

 1. Structural Directives:

       Structural Directive is associated with manipulating the DOM elements. You will find an asterisk (*) prefix before the directive. We can take *ngFor and *ngIf  ,*ngSwitch as examples here.

 2. Attribute Directives:
     ng generate directive highlight
    
       
 3. Component Directives: 
   
 [styles]
[class]

Attribute Directives examples:

1 example : Phone number mask 9898-555-545 


import { Directive, HostListener } from "@angular/core";
import { NgControl } from "@angular/forms";

@Directive({
  selector: '[formControlName][phoneMask]'
})
export class PhoneMaskDirective {
  constructor(public ngControl: NgControl) { }
  @HostListener("input", ["$event"])
  onKeyDown(event: KeyboardEvent) {
      const input = event.target as HTMLInputElement;
      let trimmed = input.value.replace(/\s+/g, "");
      if (trimmed.length > 12) {
          trimmed = trimmed.substr(0, 12);
      }
      trimmed = trimmed.replace(/-/g, "");
      let numbers = [];
      numbers.push(trimmed.substr(0, 3));
      if (trimmed.substr(3, 3) !== "") numbers.push(trimmed.substr(3, 3));
      if (trimmed.substr(6, 4) != "") numbers.push(trimmed.substr(6, 4));
      input.value = numbers.join("-");
  }
}



2.Example ZIP Code 56845

import { Directive, HostListener } from '@angular/core';
import { NgControl } from "@angular/forms";

@Directive({
  selector: '[formControlName][appZipcode]'
})
export class ZipcodeDirective {

  constructor(public ngControl: NgControl) {}
  @HostListener("input", ["$event"])
  onKeyDown(event: KeyboardEvent) {
        const input = event.target as HTMLInputElement;
        let trimmed = input.value.replace(/\s+/g, "");
        if (trimmed.length > 10) {
          trimmed = trimmed.substr(0, 10);
        }
         trimmed = trimmed.replace(/-/g, "");
            let numbers = [];
            numbers.push(trimmed.substr(0, 5));
            if (trimmed.substr(5, 4) !== "") numbers.push(trimmed.substr(5, 4));
            input.value = numbers.join("-");
          }
}



3. Two Digit Decima Number
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
  selector: '[appTwoDigitDecimaNumber]'
})
export class TwoDigitDecimaNumberDirective {
  private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];
  constructor(private el: ElementRef) {
  }
  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    let current: string = this.el.nativeElement.value;
    const position = this.el.nativeElement.selectionStart;
    const next: string = [current.slice(0, position), event.key == 'Decimal' ? '.' : event.key, current.slice(position)].join('');
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}



Numbers Only:

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

@Directive({
  selector: 'input[numbersOnly]'
})
export class NumberDirective {

@Output() valueChange = new EventEmitter()

  constructor(private el: NgControl) { }

  @HostListener('input', ['$event.target.value'])
  onInput(value: string) {
    // NOTE: use NgControl patchValue to prevent the issue on validation
    this.el.control?.patchValue(value.replace(/[^0-9]/g, ''));
  }
   

}

Decimal Number:

import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
  selector: '[decimaNumber]'
})
export class DecimaNumberDirective {
  private regex: RegExp = new RegExp(/^\d*\.?\d{0,3}$/g);
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];
  constructor(private el: ElementRef) {
  }
  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    let current: string = this.el.nativeElement.value;
    const position = this.el.nativeElement.selectionStart;
    const next: string = [current.slice(0, position), event.key == 'Decimal' ? '.' : event.key, current.slice(position)].join('');
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}


Phone Number:

import { Directive, HostListener } from "@angular/core";
import { NgControl } from "@angular/forms";

@Directive({
  selector: "[formControlName][phoneNumber]"
})
export class PhoneNumberDirective {
  constructor(public ngControl: NgControl) {}
  // or simplier add dashes US pattern mode
  @HostListener("input", ["$event"])
  onKeyDown(event: KeyboardEvent) {
    const input = event.target as HTMLInputElement;
    let trimmed = input.value.replace(/\s+/g, "");
    if (trimmed.length > 12) {
      trimmed = trimmed.substr(0, 12);
    }
    trimmed = trimmed.replace(/-/g, "");
    let numbers = [];
    numbers.push(trimmed.substr(0, 3));
    if (trimmed.substr(3, 3) !== "") numbers.push(trimmed.substr(3, 3));
    if (trimmed.substr(6, 4) != "") numbers.push(trimmed.substr(6, 4));
    input.value = numbers.join("-");
  }
}



Trim 

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

@Directive({
    selector: '[appTrim]',
})
export class TrimDirective {

    constructor(
        private el: ElementRef
    ) { }

    @HostListener('blur') onBlur() {
        const value = this.el.nativeElement.value;
        if (value) {
            this.el.nativeElement.value = value.trim();
        }
    }
}


Social Security:


import { Directive, HostListener } from "@angular/core";
import { NgControl } from "@angular/forms";

@Directive({
  selector: "[formControlName][socialSecurity]"
})
export class SocialSecurityDirective {
  constructor(public ngControl: NgControl) {}
  // or simplier add dashes US pattern mode
  @HostListener("input", ["$event"])
  onKeyDown(event: KeyboardEvent) {
    const input = event.target as HTMLInputElement;
    let trimmed = input.value.replace(/\s+/g, "");
    if (trimmed.length > 11) {
      trimmed = trimmed.substr(0, 11);
    }
    trimmed = trimmed.replace(/-/g, "");
    let numbers = [];
    numbers.push(trimmed.substr(0, 3));
    if (trimmed.substr(3, 2) !== "") numbers.push(trimmed.substr(3, 2));
    if (trimmed.substr(5, 4) != "") numbers.push(trimmed.substr(5, 4));
    input.value = numbers.join("-");
  }
}





Friday, July 22, 2022

Angular JIT and AOT

 Just-in-Time (JiT) vs Ahead-of-Time (AoT) compilation in Angular



JIT (Just-in-Time Compilation)

 Just-in-Time (JIT) is a type of compilation that compiles your app in the browser at runtime.




ng build 

ng serve

Benefits of JIT:

  • It Compiled the code in the browser.
  • Each file of the application is compiled separately.
  • This is suitable for local development.
  • If there is any binding error then Template binding errors are shown at the time of application is rendered.

AOT (Ahead-of-Time Compilation)


Ahead-of-Time (AOT) is a type of compilation that compiles your app at build time.




ng build --aot 

ng serve --aot


Benefits of AOT:

  • Faster startup as Parsing and Compilation doesn’t happen in the Browser.
  • Templates gets checked during development(which means all the errors which we see in the javascript console in the running apps otherwise will then be thrown in our build process).
  • Smaller File Size as unused Features can be stripped out and the Compiler itself isn’t shipped.

We can compare the JiT and AoT compilation as below












Wednesday, July 20, 2022

Lazy Loading

 Lazy Loading in Angular – A Beginner's Guide to NgModules

What is Lazy Loading?

Lazy loading is the process of loading components, modules, or other assets of a website as needed. 
When your Angular app loads, all app modules are loaded, whether they are required or not. Now, this may not seem like a problem if the app is small, but as its modules grow, it will slow down the entire app.










From the official docs,

By default, NgModules are eagerly loaded, which means that as soon as the application loads, so do all the NgModules, whether or not they are immediately necessary. For large applications with lots of routes, consider lazy loading —a design pattern that loads NgModules as needed. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.

Advantages of Lazy loading:

  • Faster page loads
  • Better user experience
  • Bandwidth conservation
  • Lazy loading basics


    In order to create lazy loaded modules, execute the below commands:


    ng generate m modulea --route a --module app.module

    ng generate m moduleb --route b --module app.module

    The commands will generate two folders called modulea and moduleb. Each folder will contain its own module.ts, routing.ts and component files.  

    If you check your app-routing.module.ts you will see the below code for routes:

    const routes: Routes = [{path:'a',loadChildren:()=>import('./modulea/modulea.module').then(m=>m.Moduleamodule)},
      {path:'b',loadChildren:()=>import('./moduleb/moduleb.module').then(m => m.ModulebModule) },];

    Lazy Loading 

    To lazy load the modules, go to the app-routing.module.ts file and use loadChildren. You don't need to import the module in the app-routing.module.ts but it will get imported dynamically during runtime.

    Here is how the app-routing.module.ts file looks:



    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';

    const routes: Routes = [ {path: 'a', loadChildren: () => import('./modulea/modulea.module').then(m => m.moduleaModule)}, {path: 'b', loadChildren: () => import('./moduleb/moduleb.module').then(m => m.modulebModule)} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] })
    export class AppRoutingModule { }


    Conclusion

    In this article, you used lazy loading routes in an Angular application. Lazy loading is an important Angular feature that helps to reduce the initial load time since it loads only the necessary files first.


    Angular Local Storage


     What is Local Storage?

    1. Local storage is client-side storage for web applications.
    2. It stays there as long as it's not cleared unlike session storage, which lasts for the current browser tab session.


     How will Work with Local storage:

    •  localStorage.setItem()
    •  localStorage.getItem()
    • localStorage.removeItem()
    • localStorage.clear()

     LocalStorage.setItem

    The  SetItem method allows you to add a value to the local storage. It stores data using a key-value pair.

    localStorage.setItem('Token_Key')

     LocalStorage.getItem

    The  GetItem allows you to read back the data saved in local storage using the same key.

    localStorage.getItem('Token_Key')


     LocalStorage.removeItem

    Once you are done using the data in the local storage, you can remove it using the  RemoveItem method.

    localStorage.removeItem('Token_Key')


     LocalStorage.clear

    You can Clear all of the data out of the local storage using the clear method to wipe the slate clean.

    localStorage.Clear()


    how to call api in angular

                                Api Call in service file Making API calls is a common task in Angular applications, and it can be achieved using...