在输入的每 4 位数字后添加空格 [英] Add space after every 4th digit in input
本文介绍了在输入的每 4 位数字后添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在输入的每 4 个数字后添加一个空格,我在控制台中得到了这个,我如何才能实现这一点以在 Angular 5 中更改输入.
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.
我使用的代码如下 .ts
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. ">
控制台:
1
11
111
1111
1111 1
1111 11
1111 111
1111 1111
1111 1111 1
1111 1111 11
1111 1111 111
1111 1111 1111
我改编自 Angular 2 : input 中每 4 位后加连字符,卡号输入.但我把连字符改成了空格.
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.
推荐答案
我建议查看此指令
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(' ');
}
}
并在您的 html
模板中用作
and use in your html
template as
<input type="text" credit-card>
这里是源代码
更新:(2019 年 10 月 10 日)输入类型应仅为 text
(默认类型)
UPDATE: (10/10/2019)
Input type should be only text
(default type)
这篇关于在输入的每 4 位数字后添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文