srujana
srujana

Reputation: 453

How to insert space after two digits in ion-input field in angular2?

I am working on ionic2 application. Here I need to display an input field in the way that when user entered two digits then a space must be added to the digits means for every pair of digits an empty space has to be added. I had tried to implement this using jQuery. But in ionic2 $(this).val() is not working. Is there any way to implement this pattern?

Below is my code.

toothFn(value) {
  console.log("tooth");
  console.log("toothvalue",value); 
  var foo = value.split(" ").join("");
  if (foo.length > 0) {
    console.log("if");
    foo = foo.match(new RegExp('.{1,2}', 'g')).join(" ");
  }
  console.log("foo", foo);
  return foo;
}
 <ion-list>
 <ion-item>
   <ion-label floating>Tooth Number</ion-label>
   <ion-input type="number" (input)="input = toothFn(input)" oninput="this.value = Math.abs(this.value)" formControlName="toothNum" id="toothNum">
   </ion-input>
 </ion-item>
 <ion-item *ngIf="caseform.controls.toothNum.hasError('required') && caseform.controls.toothNum.touched">
   <p style="color:red">please enter the tooth number!</p>
 </ion-item>
</ion-list>

Upvotes: 0

Views: 1513

Answers (1)

dev_in_progress
dev_in_progress

Reputation: 2494

Not sure for exact pattern but you could check for every keyup event on your input.

For example.

  <ion-input [(ngModel)]="textNumber" (keypress)="validate($event)" (keyup)="addSpace()"></ion-input>

  addSpace(){

    //first remove previous spaces
    this.textNumber = this.textNumber.replace(/\s/g, '');

    //then add space (or any char) after second (or any "n-th") position
    this.textNumber = this.chunk(this.textNumber, 2).join(' ');
  }

  //validate and only allow numbers
  validate(event){
      return event.charCode >= 48 && event.charCode <= 57;
  }

  chunk(str: any, position: number){
    let ret = [];
    let i;
    let len;

    for(i = 0, len = str.length; i < len; i += position) {
       ret.push(str.substr(i, position));
    }

    return ret;
  }

Here is an simple example: https://stackblitz.com/edit/input-check

Ps. type="number" defines a numeric input field and floating point numbers, that means it's not only restricted to numbers, you can, for example, add char e because e is mathematical constant.

Upvotes: 2

Related Questions