Many of ours apps at some point will require a form with user input. More often than not, a phone number input is required. Rather than simply have the digits, it can be helpful to format the number as its typed in. It's much more visibly appealing and easier to find a mistake if there is one.
To do this in a form will require a few steps. We will need a form input for the number. We will need a directive to listen for input changes. Finally, we will need a pipe to tap into the phone formatting itself.
First things first is creating the telephone format pipe. To do this, we'll need to import the libphonenumber-js package by Nikolay Kuchumov. The pipe will take a number or phone input and use the the United States phone formatting:
// phone.pipe.ts
import { Pipe, PipeTransform } from "@angular/core";
import { AsYouType } from "libphonenumber-js";
@Pipe({
name: "phone",
})
export class PhonePipe implements PipeTransform {
transform(phoneValue: number | string): string {
let ayt = new AsYouType("US");
try {
ayt.input(phoneValue + "");
return ayt.getNumber().formatNational();
} catch (error) {
console.log(error);
return phoneValue;
}
}
}
We can see here that regardless of input type we'll return a string. The inputted value will be me made into a string (if it's not already) and used to create an AsYouType object. Then, we'll return the value as the national phone number format. If there is an error along the way, the original phone number value will be returned instead.
Next, we'll set up the directive to use this phone number pipe. We will listen to a couple different changes to the input: model change event and the backspace event. On each of those events, the input value will be sent through the pipe for formatting. This will look as follows:
// phone-mask.directive.ts
import { Directive, HostListener } from "@angular/core";
import { NgControl } from "@angular/forms";
import { PhonePipe } from "../pipes/phone.pipe";
@Directive({
selector: "[phoneMask]",
})
export class PhoneMaskDirective {
constructor(public ngControl: NgControl, private phonePipe: PhonePipe) {}
@HostListener("ngModelChange", ["$event"])
onModelChange(event) {
this.ngControl.valueAccessor.writeValue(
this.phonePipe.transform(event)
);
}
@HostListener("keydown.backspace", ["$event"])
keydownBackspace(event) {
this.ngControl.valueAccessor.writeValue(
this.phonePipe.transform(event.target.value)
);
}
}
Now we'll create our form with a telephone input. But first, we'll need to allow the page in which that form resides to use the directive and the pipe. So, we'll create a module out of the directive, then import that module to the page's module, as well as add the phone pipe as a provider for the form's page. We'll also need the ReactiveFormsModule
too for later use.
// phone-mask.directive.ts
...
export class PhoneMaskDirective {
...
}
@NgModule({
declarations: [PhoneMaskDirective],
exports: [PhoneMaskDirective],
})
export class PhoneMaskDirectiveModule {}
// home.module.ts
...
import { PhonePipe } from "../phone.pipe";
import { PhoneMaskDirectiveModule } from "../phone-mask.directive";
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
IonicModule,
HomePageRoutingModule,
PhoneMaskDirectiveModule,
],
declarations: [HomePage],
providers: [PhonePipe],
})
export class HomePageModule {}
With those tools usable, we'll create the input on the page and add the directive to mask the inputted value:
// home.page.html
...
<ion-content [fullscreen]="true">
<form [formGroup]="form" (ngSubmit)="submit()">
<ion-input
type="tel"
formControlName="phone"
placeholder="Phone Number"
clearInput="true"
autofocus="true"
inputmode="tel"
phoneMask
(keyup.enter)="submit()"
>
</ion-input>
</form>
</ion-content>
This input is inside of a form. The form here is mainly just to show you how to get the digits back on submit. The type of the ion-input
is set to "tel", as well as the input mode. I've done this so when on a mobile device the only tappable buttons should be numbers. There is a keyup.enter
event so we can hit the submit fuction on enter button. Also, of course, we have the directive.
The typescript side of this will look as follows:
// home.page.ts
import { Component } from "@angular/core";
import { FormBuilder, FormGroup } from "@angular/forms";
@Component({
selector: "app-home",
templateUrl: "home.page.html",
styleUrls: ["home.page.scss"],
})
export class HomePage {
public form: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group({
phone: [""],
});
}
public submit() {
console.log(`Phone: ${this.digitsOnly(this.f.phone.value)}`);
}
get f() {
return this.form.controls;
}
private digitsOnly(str: string) {
return str.replace(/\D/g, "");
}
}
The above code shows how to set up the form using FormGroup
and FormBuilder
. Then have helper functions to get to the form controls, as well as get the digits form the masked phone string. All of this considered, we get the following result:
To get a full copy of the code, you can visit the repository here.
Top comments (0)