12

I am trying to create a directive for formatting and validating the phone numbers in my angualr 4 application, was looking for some guidance to getting started.

ram_p
  • 123
  • 1
  • 4

1 Answers1

14

Edited (15.03.2018) - thanks @Joseph Webber

First, you have to install libphonenumber-js, which is a wrapper of google-libphonenumber ready to be imported on Angular 2+. You can install it on your app with:

npm install libphonenumber-js --save

or

yarn add libphonenumber-js

depending on the package manager you use.

After install you can use it on your component like:

import { Component, OnInit } from '@angular/core';
import { parse, format, AsYouType } from 'libphonenumber-js';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  asYouType: any;
  format: any;
  parse: any;

  ngOnInit() {
    this.asYouType = new AsYouType('US').input('2133734');
    this.format = format('2133734253', 'US', 'International');
    this.parse = parse('(0777) 844 822', 'RO');
  }

}

I added the working demo on Github:

libphonenumber-demo-angular2

BogdanC
  • 2,746
  • 2
  • 24
  • 22
  • I installed using npm as you mentioned above and when i import the 'libphonenumber-js' I am getting the error as cannot fine module 'libphonenumber-js'. – ram_p Jul 12 '17 at 14:26
  • `asYouType` name is deprecated, use `AsYouType` instead. https://github.com/catamphetamine/libphonenumber-js/blob/master/CHANGELOG.md#0450--20012018 – Joseph Webber Mar 15 '18 at 18:29