角度2:在输入的每4位数字,卡号输入之后添加连字符 [英] Angular 2 : add hyphen after every 4 digit in input , card number input
问题描述
我需要在输入的每4位数字后添加一个连字符,我要在控制台中获取它,我如何才能在角度2的输入中实现这一点
i need to add an hyphen after every 4 digit i enter, i am getting this in the console , how can i can achieve this to change in the input in angular 2
我使用的代码如下 .ts
mychange(val){
var self = this;
var chIbn = self.storeData.iban_no.split("-").join("");
if (chIbn.length > 0) {
chIbn = chIbn.match(new RegExp('.{1,4}', 'g')).join("-");
}
console.log(chIbn);
self.storeData.iban_no = chIbn;
}
HTML
<input type="text" name="din" (ngModelChange)="mychange($event)" class="form-control" [(ngModel)]="storeData.iban_no" required>
控制台
输入
需要输入本身的连字符值
need that hyphen value in input itself
推荐答案
您需要进行以下更改
<input type="text" name="din" (ngModelChange)="mychange($event)"
class="form-control" [ngModel]="iban_no" required>
您不需要[(ngModel)]
只需保持[ngModel]
即可,因为您正在处理更改事件,并且通过这样的方法,您无需在角度this
中使用self
就可以了.>
you don't need [(ngModel)]
just keep [ngModel]
as you are taking care of change event and from method do like this, you don't need self
in angular this
will be okay.
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.iban_no = chIbn;
}
方法中也存在问题,在尝试修改val
为属性分配值时,您需要直接使用val
而不是属性.
there is issue in your method too, you need to use val
instead of property directly as you are trying to modify val
as assigning value to property.
这篇关于角度2:在输入的每4位数字,卡号输入之后添加连字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!