Angular Decimal Validation

Introduction Angular Directives

 
Directives are instructions to the DOM.
 
There are three types of directives:
  1. Component 
  2. Structural directive
  3. Attribute directive
Component
 
Directives with a template
 
Structural Directive
 
Change the DOM layout by adding and removing DOM elements.(leading with *).
 
Attribute Directive
 
Change the appearance or behavior of an element 
 

List of Angular Directives

  • *ngIf
    The NgIf directive is used when you want to display or remove an element based on a condition. If the condition is false the element the directive is attached to will be removed from the DOM.

    The syntax is: *ngIf="<condition>"

  • *ngFor
    Its point is to repeat a given HTML template once for each value in an array, each time passing it the array value as context for string interpolation or binding.

    Syntax: <li *ngFor="let user of listuser">

  • ngClass
    The NgClass directive allows you to set the CSS class dynamically for a DOM element.

  • ngStyle
    The NgStyle directive lets you set a given DOM elements style properties.

  • ngSwitch
    This directive allows us to render different elements depending on a given condition.
Step 1
 
Let's create an Angular project using the following npm command,
 
Angular Decimal Validaion
 
Step 2
 
Open the created project in the Visual Studio code and generate directive by using below command,
 
Angular Decimal Validaion 
 
Step 3
 
Open the created decimalvalidation.directive.ts,
 
Angular Decimal Validaion
 
selector
 
Selector tells Angular to create and insert an instance of this component where it finds <product-desc> tag. For example, if an app’s HTML contains <product-desc></product-desc>, then Angular inserts an instance of the Product Description view between those tags. 
 
Your HTML just uses it as Attribute for an element
 
Step 4
 
Let's open the decimalvalidation.directive.ts Use the below regular expression code for Decimal Validation, 
  1. import {  
  2.     Directive,  
  3.     ElementRef,  
  4.     HostListener  
  5. } from '@angular/core';  
  6. @Directive({  
  7.     selector: '[appDecimalvaliation]'  
  8. })  
  9. export class DecimalvalidaitonDirective {  
  10.     private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);  
  11.     private specialKeys: Array < string > = ['Backspace''Tab''End''Home''-''ArrowLeft''ArrowRight''Del''Delete'];  
  12.     constructor(private el: ElementRef) {}  
  13.     @HostListener('keydown', ['$event'])  
  14.     onKeyDown(event: KeyboardEvent) {  
  15.         // Allow Backspace, tab, end, and home keys     
  16.         if (this.specialKeys.indexOf(event.key) !== -1) {  
  17.             return;  
  18.         }  
  19.         let current: string = this.el.nativeElement.value;  
  20.         const position = this.el.nativeElement.selectionStart;  
  21.         const next: string = [current.slice(0, position), event.key == 'Decimal' ? '.' : event.key, current.slice(position)].join('');  
  22.         if (next && !String(next).match(this.regex)) {  
  23.             event.preventDefault();  
  24.         }  
  25.     }  
  26. }  
Regular Expression
 
A regular expression is an object that describes a pattern of characters. Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text.
 
ElementRef
 
It is a service, which gives us access to the DOM Object. The ElementRef gives the directive direct access to the DOM element upon which it’s attached.
 
HostListener
 
This decorator allows us to subscribe to the events which is raised from the DOM element. Listen to the event occurs on the element and act accordingly. This is a function decorator that accepts an event name. When that event gets fired on the host element it calls the associated function.
 
keydown
 
The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value.
 
Step 6
 
And finally open the app.component.html file add the attribute name.
 
<inputtype="text"autocomplete="off"maxlength="15"appDecimalvaliation>
 

Summary

 
In this article, we discussed how to validate decimal pattern using directive.


Similar Articles