Reputation: 1839
I try to create a numbers / numeric input only directive, which means I want to allow a input such as: 451,45 or 451.45
Currently the directive looks like this:
import {Directive, ElementRef, HostListener, Input} from '@angular/core';
@Directive({
selector: '[numbers-only]'
})
export class NumbersOnlyDirective {
private el: HTMLElement;
constructor(el: ElementRef) {
this.el = el.nativeElement;
}
@HostListener('keydown', ['$event']) onKeyDown(e: Event) {
}
}
The next step would be to fetch the current value of the element, and reformat if every time on a key down event. My question : How do I get the current value of the directive, I cant figure out how to get it from the ElementRef. And what would be the best way to format the input: Regex ?
Thank you for your patience and ideas!
Upvotes: 0
Views: 3124
Reputation: 1800
You can use the keyup event, as this is when the value will be updated. And you do not need a RegEx
for that you can just check the range of the keyCode
. See this plunkr:
http://plnkr.co/edit/xyAy2KjPia1qncqAcpMj?p=preview&open=app%2Fapp.component.ts
Upvotes: 1