Tuesday 16 January 2018

Custom directive in angular 2(Max number only )

Create a Directive ts file in your project=>


import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[limitToMax]'
})
export class limitToMaxDirective {
@Input() lastPage: string;
constructor(private element: ElementRef) { }
@HostListener('keyup') onMouseEnter() {
if (Number(this.element.nativeElement.value) >
Number(this.element.nativeElement.max) &&
this.element.nativeElement.keyCode != 46 && // delete
this.element.nativeElement.keyCode != 8 // backspace
) {
this.element.nativeElement.value = this.lastPage;
}
}

}

How to use this directive in your project=>


<input #pageInput type="number" class="form-control"
limitToMax
[lastPage]="page"
min="1"
step="1"
max="{{maxPage}}"
[ngModel]="page"
(blur)="page = pageInput.value > maxPage || pageInput.value < 1 ?
pageInput.value=page : pageInput.value"
(keyup.enter)="page = pageInput.value > maxPage || pageInput.value < 1 ?
pageInput.value=page : pageInput.value"
(keyup.esc)="pageInput.value = page"
/>


This directive must be DECLARATION  in the module.

import {limitToMaxDirective} from './utils/limittomax.Directive';
@NgModule({
imports: [ CommonModule, FormsModule ],
declarations: [limitToMaxDirective]
})