Sunday, September 25, 2022

Angular Log in Form

Login Form Using Reactive Forms:




App.component.html

<div class="container"> 
  <form [formGroup]="formloginGroup" (ngSubmit)="onSubmit(formGroup.value)" class="form">

    <mat-form-field floatLabel="never" class="form-element">
      <input type="text" matInput placeholder="Username" formControlName="username">
      <mat-error *ngIf="formGroup.controls['username'].invalid">
        {{getError('user')}}
      </mat-error>
    </mat-form-field>

    <mat-form-field floatLabel="never" class="form-element">
      <input type="password" matInput placeholder="Password" formControlName="password">
      <mat-error *ngIf="!formGroup.controls['password'].valid">
        {{getError('pass')}}
      </mat-error>
    </mat-form-field>

    <div class="form-element">
      <button mat-raised-button color="primary" type="submit" class="button" 
[disabled]="!formGroup.valid">Submit Form</button>
    </div>

  </form>
</div>

app.component.ts

import { Component } from '@angular/core';
import { FormBuilderFormGroupFormControlValidators } from '@angular/forms';
import { Observable }    from 'rxjs/Observable';

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

  formGroupFormGroup;
  constructor(private formBuilderFormBuilder) { }

  ngOnInit() {
    this.createForm();
  }

  createForm() {
    this.formloginGroup = this.formBuilder.group({
      'username': [''Validators.required],
      'password': [''Validators.required],
    });
  }


  getError(el) {
    switch (el) {
      case 'user':
        if (this.formloginGroup.get('username').hasError('required')) {
          return 'Username required';
        }
        break;
      case 'pass':
        if (this.formloginGroup.get('password').hasError('required')) {
          return 'Password required';
        }
        break;
      default:
        return '';
    }
  }

  onSubmit(post) {
    // this.post = post;
  }

}



app.component.css


.container {
  padding10px;
}

.form {
  min-width150px;
  max-width500px;
  width100%;
}

.form-element {
  padding5px 0px 25px 2px;
  width100%;
}

.button {
  width100%;
}


app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { ReactiveFormsModule } from '@angular/forms';

import { MaterialModule } from './material.module';
import { AppComponent } from './app.component';

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


Register Form:


register.component.html

<div class="register-form">
  <form [formGroup]="form" (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label>Full Name</label>
      <input
        type="text"
        formControlName="fullname"
        class="form-control"
        [ngClass]="{ 'is-invalid': submitted && f.fullname.errors }"
      />
      <div *ngIf="submitted && f.fullname.errors" class="invalid-feedback">
        <div *ngIf="f.fullname.errors.required">Fullname is required</div>
      </div>
    </div>

    <div class="form-group">
      <label>Username</label>
      <input
        type="text"
        formControlName="username"
        class="form-control"
        [ngClass]="{ 'is-invalid': submitted && f.username.errors }"
      />
      <div *ngIf="submitted && f.username.errors" class="invalid-feedback">
        <div *ngIf="f.username.errors.required">Username is required</div>
        <div *ngIf="f.username.errors.minlength">
          Username must be at least 6 characters
        </div>
        <div *ngIf="f.username.errors.maxlength">
          Username must not exceed 20 characters
        </div>
      </div>
    </div>

    <div class="form-group">
      <label>Email</label>
      <input
        type="text"
        formControlName="email"
        class="form-control"
        [ngClass]="{ 'is-invalid': submitted && f.email.errors }"
      />
      <div *ngIf="submitted && f.email.errors" class="invalid-feedback">
        <div *ngIf="f.email.errors.required">Email is required</div>
        <div *ngIf="f.email.errors.email">Email is invalid</div>
      </div>
    </div>

    <div class="form-group">
      <label>Password</label>
      <input
        type="password"
        formControlName="password"
        class="form-control"
        [ngClass]="{ 'is-invalid': submitted && f.password.errors }"
      />
      <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
        <div *ngIf="f.password.errors.required">Password is required</div>
        <div *ngIf="f.password.errors.minlength">
          Password must be at least 6 characters
        </div>
        <div *ngIf="f.password.errors.maxlength">
          Username must not exceed 40 characters
        </div>
      </div>
    </div>

    <div class="form-group">
      <label>Confirm Password</label>
      <input
        type="password"
        formControlName="confirmPassword"
        class="form-control"
        [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }"
      />
      <div
        *ngIf="submitted && f.confirmPassword.errors"
        class="invalid-feedback"
      >
        <div *ngIf="f.confirmPassword.errors.required">
          Confirm Password is required
        </div>
        <div *ngIf="f.confirmPassword.errors.matching">
          Confirm Password does not match
        </div>
      </div>
    </div>

    <div class="form-group form-check">
      <input
        type="checkbox"
        formControlName="acceptTerms"
        class="form-check-input"
        [ngClass]="{ 'is-invalid': submitted && f.acceptTerms.errors }"
      />
      <label for="acceptTerms" class="form-check-label"
        >I have read and agree to the Terms</label
      >
      <div *ngIf="submitted && f.acceptTerms.errors" class="invalid-feedback">
        Accept Terms is required
      </div>
    </div>

    <div class="form-group">
      <button type="submit" class="btn btn-primary">Register</button>
      <button
        type="button"
        (click)="onReset()"
        class="btn btn-warning float-right"
      >
        Reset
      </button>
    </div>
  </form>
</div>



register.component.ts

import { ComponentOnInit } from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators
from '@angular/forms';
import Validation from './utils/validation';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  formFormGroup;
  submitted = false;

  constructor(private formBuilderFormBuilder) {}

  ngOnInit(): void {
    this.form = this.formBuilder.group(
      {
        fullname: [''Validators.required],
        username: [
          '',
          [
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(20)
          ]
        ],
        email: ['', [Validators.requiredValidators.email]],
        password: [
          '',
          [
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(40)
          ]
        ],
        confirmPassword: [''Validators.required],
        acceptTerms: [falseValidators.requiredTrue]
      },
      {
        validators: [Validation.match('password''confirmPassword')]
      }
    );
  }

  get f(): { [keystring]: AbstractControl } {
    return this.form.controls;
  }

  onSubmit(): void {
    this.submitted = true;

    if (this.form.invalid) {
      return;
    }

    console.log(JSON.stringify(this.form.valuenull2));
  }

  onReset(): void {
    this.submitted = false;
    this.form.reset();
  }
}


Angular Sign Out Condition

 Angular Sign Out Button Condition:





  app.component.html


 <button class="signout_button" (click)="signout()">sign out <button>

app.component.ts 

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

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

export class AppComponent implements OnInit {
 
 constructor(private router: Router) {}

  ngOnInit(): void {
  }
  signout(){
   
  }

}

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.


    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...