Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Custom Pipe not Updating Until Object Saved

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!

like image 225
pjlamb12 Avatar asked Mar 18 '26 15:03

pjlamb12


1 Answers

You need to add some action for the ngModelChange event

<input type="text" [ngModel]="obj.phone | phone" (ngModelChange)="obj.phone=$event" />
like image 98
Günter Zöchbauer Avatar answered Mar 20 '26 06:03

Günter Zöchbauer