Search code examples
angulartypescriptangular5

Add space after every 4th digit in credit card 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.


Solution

  • 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)