Angular directives are one of the core features in the angular framework; directives help to extend the HTML functionality and structure, modify the elements, and attach to the DOM.
Angular Predefined directives
ngClass,ngStyle,ngIf,ngFor,ngswitch
What is the purpose of creating the custom directives?
In real-time application development, we often have to use the same repeated functionality throughout the application and maintain consistency and reusability.
Example
Allow the numbers only in the registration form, if the user enters text the input field will block the text.
Create the custom directive
ng g directive Directive/AollwNumber
AollwNumber.ts
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appAllowNumber]'
})
export class AllowNumberDirective {
// Allow numbers.
private regex: RegExp = new RegExp(/^\d+$/);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', 'ArrowLeft', 'ArrowRight', 'Delete'];
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
debugger
const selecetdText = window.getSelection().toString();
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
let current: string = this.el.nativeElement.value;
if(selecetdText != "" && current.indexOf(selecetdText) !== -1){
current = current.slice(0,current.indexOf(selecetdText));
}
// We need this because the current value on the DOM element
// is not yet updated with the value from this event
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
} else if (event.currentTarget['max'] != "undefined" && event.currentTarget['max'] != "" && event.currentTarget['max'] != null && !(Number(event.currentTarget['max']) >= Number(next))) {
event.preventDefault();
}
if(event.currentTarget['min'] != "undefined" && event.currentTarget['min'] != "" && event.currentTarget['min'] != null && !(Number(event.currentTarget['min']) <= Number(next)) ){
event.preventDefault();
}
}
/**
* This is for restrict paste value in input field
* @param e
*/
@HostListener('paste', ['$event']) blockPaste(e: KeyboardEvent) {
e.preventDefault();
}
}
Register the directive App module
After the creation of the directive, this is required to be registered in the root directive module or app module.
Decore directive in the Input Field