Angular 2 : add hyphen after every 4 digit in input , card number input

丶灬走出姿态 提交于 2019-12-18 09:26:55

问题


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

Code i used given below .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>

Console

input

need that hyphen value in input itself


回答1:


You need to do changes as below

<input type="text" name="din" (ngModelChange)="mychange($event)"  
class="form-control" [ngModel]="iban_no"   required>

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;
  }

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:


Create a directive to achieve this.

You can use the HostBinding feature to get the element to which the directive is attached to and retrieve the value of the element and do your manipulations to the value.



来源:https://stackoverflow.com/questions/49421414/angular-2-add-hyphen-after-every-4-digit-in-input-card-number-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!