I need to add a space after every 4th digit I enter, I am getting this in the console, how can I can achieve this to change in the input in Angular 5.
Code I used given below .ts
mychange(val) {
const self = this;
let chIbn = val.split(' ').join('');
if (chIbn.length > 0) {
chIbn = chIbn.match(new RegExp('.{1,4}', 'g')).join(' ');
}
console.log(chIbn);
this.id = chIbn;
}
HTML
<input class="customerno" (ngModelChange)="mychange($event)" [formControl]="inputFormControl" (keydown.backspace)="onKeydown($event)" maxlength="{{digit}}" (keyup)="RestrictNumber($event)" type="tel" matInput [(ngModel)]="id" placeholder="Customer No. ">
Console:
1
11
111
1111
1111 1
1111 11
1111 111
1111 1111
1111 1111 1
1111 1111 11
1111 1111 111
1111 1111 1111
I adapted it from Angular 2 : add hyphen after every 4 digit in input , card number input. but I changed the hypen to a space.
Using plain-JavaScript, I'd suggest: function space(el, after) { // defaults to a space after 4 characters: after = after || 4; /* removes all characters in the value that aren't a number, or in the range from A to Z (uppercase): */ var v = el. value.
To add space between numbers with JavaScript, we use the number toLocaleString method. const num = 1234567890; const result = num. toLocaleString("fr"); to call num.
I would recommend to check out this Directive
import { Directive, HostListener, ElementRef } from '@angular/core';
@Directive({
selector: '[credit-card]'
})
export class CreditCardDirective {
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
let trimmed = input.value.replace(/\s+/g, '');
if (trimmed.length > 16) {
trimmed = trimmed.substr(0, 16);
}
let numbers = [];
for (let i = 0; i < trimmed.length; i += 4) {
numbers.push(trimmed.substr(i, 4));
}
input.value = numbers.join(' ');
}
}
and use in your html
template as
<input type="text" credit-card>
Here is the source code
UPDATE: (10/10/2019)
Input type should be only text
(default type)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With