I've created a directive to limit the length of input
field type=number
.
// Input
<input min="1" appLimitTo [limit]="5" type="number" name="property" [(ngModel)]="property">
// Directive
import {Directive, HostListener, Input} from '@angular/core';
@Directive({
selector: '[appLimitTo]',
})
export class LimitToDirective {
@Input() limit: number;
@Input() ngModel: any;
@HostListener('input', ['$event'])
onInput(e) {
if (e.target.value.length >= +this.limit) {
e.target.value = (e.target.value).toString().slice(0, this.limit - 1);
e.preventDefault();
}
}
}
It works fine if we enter the value through the keyboard. But the problem arises when if I copy & paste 12345678913465789
this number, this line e.target.value = (e.target.value).toString().slice(0, this.limit - 1);
shorten it to the limit, but the ngModel
still contains 12345678913465789
value. How to update this ngModel value?
Please help.
PS - What should I add in my directive to meet the requirement?