角度5:在输入的每4位数字后添加空格

And*_*aha 3 angular angular5

我需要在输入的每4位数字后添加一个空格,我要在控制台中获取它,我如何才能实现这一点来更改角度5的输入

我在以下.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;
  }
Run Code Online (Sandbox Code Playgroud)

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. ">
Run Code Online (Sandbox Code Playgroud)

安慰

1
11
111
1111
1111 1
1111 11
1111 111
1111 1111
1111 1111 1
1111 1111 11
1111 1111 111
1111 1111 1111
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

注意:我从Angular 2改编而成:输入,卡号输入中每4位数字后添加连字符。但是我用空间改变了hypen

Cof*_*Tea 6

我建议您查看此指令

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(' ');

  }
}
Run Code Online (Sandbox Code Playgroud)

并在您的html模板中使用

<input type="text" credit-card>
Run Code Online (Sandbox Code Playgroud)

这是 源代码

更新:(10/10/2019)输入类型应仅为text(默认类型)