Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add space after every 4th digit in input

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

enter image description here

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.

like image 620
Andika Ristian Nugraha Avatar asked May 31 '18 08:05

Andika Ristian Nugraha


People also ask

How to add space in text field using JavaScript?

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.

How do I add a space between numbers in JavaScript?

To add space between numbers with JavaScript, we use the number toLocaleString method. const num = 1234567890; const result = num. toLocaleString("fr"); to call num.


1 Answers

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)

like image 91
Coffee-Tea Avatar answered Oct 13 '22 01:10

Coffee-Tea