I have made a custom Angular 2 pipe to format a phone number from a string of 10 digits to be 'XXX-XXX-XXXX'. The pipe I made works great, but it doesn't update until you edit and then save. It doesn't update on keypress.
I've read a few different places what I could on custom pipes, but I'm not sure which route to go from here. Here's a plunk with the working custom pipe and here's the code as well:
Component:
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2>Hello {{name}}</h2>
Phone: <input type="text" [ngModel]="obj.phone | phone" />
</div>
`,
directives: [],
pipes: [PhoneNumber]
})
export class App {
public obj: any = {
phone: '8885552233'
};
constructor() {
this.name = 'Angular2'
}
}
Pipe:
import {PipeTransform, Pipe} from 'angular2/core';
@Pipe({
name: 'phone'
})
export class PhoneNumber implements PipeTransform{
transform(value, args) {
if( value ) {
var str = "";
switch( value.length ) {
case 0:
case 1:
case 2:
case 3:
str = value;
break;
case 4:
case 5:
case 6:
str = value.substring(0, 3) + '-' + value.substring(2, value.length);
break;
case 7:
case 8:
case 9:
case 10:
str = value.substring(0, 3) + '-' + value.substring(3, 6) + '-' + value.substring(6);
break;
}
return str;
} else {
return value;
}
}
}
If you have any ideas or any advice, I'd really appreciate it!
Thanks!
You need to add some action for the ngModelChange event
<input type="text" [ngModel]="obj.phone | phone" (ngModelChange)="obj.phone=$event" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With