shokha
shokha

Reputation: 3189

Add plus sign "+" before input value in Angular2

The question sounds pretty easy, but I could found any clear solution for it.

I have custom input field (I'm using reactive forms approach) for phone numbers. The aim is to always have a plus sign before input value.

Requirements:

How can we implement this logic in Angular2 project?

Upvotes: 2

Views: 2710

Answers (2)

End
End

Reputation: 636

I put something together quickly, the code needs refactoring but in essence it does what you have asked for. You can subscribe to the valueChanges event on the formControl, here you can do all the modification to the value that you need to produce the desired result. Link to Stackblitz: https://stackblitz.com/edit/angular-9mubgr

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  name = 'Angular';
  myForm: FormGroup;
  constructor() {
    this.myForm = new FormGroup({
      'myInput': new FormControl('')
    })
  }


  ngOnInit() {
    this.myForm.get('myInput').valueChanges.subscribe((inputValue) => {
      if(inputValue === this.myForm.get('myInput')) {
        return;
      }

      if(inputValue.length === 0) {
        return;
      }

      if(inputValue.legth !== 0 && inputValue.slice(0,1) !== '+') {
        this.myForm.get('myInput').setValue('+' + this.myForm.get('myInput').value);
      }
    });
  }

  patch() {
    this.myForm.patchValue({ 'myInput': '123' })
  }
}

Upvotes: 1

Tim Klein
Tim Klein

Reputation: 2778

Here is a function that you could bind to the (change) event of your input:

processInput(inputVal: string = null) {
    if (!inputVal) {
        inputVal = this.myForm.get('myInput').value; // since you're using reactive forms
    }

    if (inputVal === '') {
        // Do nothing
    } else if (inputVal.match(/^\d*$/)) {
        if (!inputVal.includes('+')) {
            inputVal = '+' + inputVal;
        }
    }

    // Then patch your 'myInput' value in your form with 'inputVal'
    this.myForm.patchValue({ 'myInput': inputVal });
}

safePatchMyInput(value: string) {
    this.processInput(value);
}

This implementation will add a plus sign if (and only if) the input string contains purely numbers. It also allows you to empty the input entirely (including the plus sign).

Edit: The addition of the safePatchMyInput method will allow you to manually patch that input and still utilize the same input processing from the previous funciton. (This means adding the default parameter to the previous funciton)

Binding to the (change) event on your input would simply look like this:

<input (change)="processInput()"/>

Edit 2

Here is an updated solution that works with FormControl.registerOnChange to process the input even if it was set manually via patchValue.

Angular Component:

myForm: FormGroup;

constructor() {
  this.myForm = new FormGroup({
    'myInput': new FormControl('')
  })
}

ngOnInit() {
  const myInput = this.myForm.get('myInput') as FormControl;
  myInput.registerOnChange(this.processInput);
}

processInput = () => {
  let inputVal = this.myForm.get('myInput').value;

  if (inputVal === '') {
    // Do nothing
  } else if (inputVal.match(/^\d*$/)) {
    if (!inputVal.includes('+')) {
      inputVal = '+' + inputVal;

      // Then patch your 'myInput' value in your form with 'inputVal'
      this.myForm.patchValue({ 'myInput': inputVal });
    }
  }
}

HTML Template:

<form [formGroup]="myForm">
    <input formControlName="myInput" (input)="processInput()"/>
</form>

Stackblitz, for reference.

Upvotes: 1

Related Questions