9

I want to mask a field for example: having phone number of 10 digit (123-123-1234) I need to mask in such a way that (xxx-xxx-1234). Also While submit the page I need to send original variable (123-123-1234) to service.

Any help would be greatly appreciated.

Thanks.

Lucifer
  • 784
  • 2
  • 7
  • 20

3 Answers3

4

It's a good example to use Angular's pipe:

Create a pipe: mask.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'mask' })
export class MaskPipe implements PipeTransform {
    transform(phrase: string) {    
        let toBeReplaced = phrase.slice(0, 7);
        return phrase.replace(toBeReplaced, "xxx-xxx");
    }
}

Put the pipe in declarations of your module:

import { MaskPipe } from "./mask.pipe";
@NgModule({
    declarations: [ MaskPipe ]
    // ...
})

Use the pipe in your template:

// Component's class:

export class AppComponent  {
    number: string = "123-123-1234";
}

// Component's template:

<h1> {{ number | mask }}</h1>

The value of number doesn't change, only the displayed value change

Faly
  • 13,291
  • 2
  • 19
  • 37
  • 1
    Faly, I think this could be possible for static variable. How about dynamic variable. Consider user is entering the phone number in text box have to mask. – Lucifer Jul 04 '17 at 12:48
4

You can create a pipe for it like below:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'mask'
})
export class NumberMaskPipe implements PipeTransform {
  transform(number: string): string {
    const visibleDigits = 4;
    let maskedSection = number.slice(0, -visibleDigits);
    let visibleSection = number.slice(-visibleDigits);
    return maskedSection.replace(/./g, '*') + visibleSection;
  }
}

And in your component you can do:

export class PhoneNumberComponent implements OnInit {
  phoneNumber: string;

  constructor() {}

  ngOnInit() {
    this.phoneNumber = "2131232131238867";
  }
}

Finally in the component:

<p>Your phone number is: {{ phoneNumber | mask }}</p>

Pipe here is dynamic so even if user enters different number of digits it will only mask till but not the last four digits. Please try the example with different number of digits as well.

Here's a working plunker:https://plnkr.co/edit/NKRQpVB1Darw8MxrqucP?p=preview

Aakash Thakur
  • 3,837
  • 10
  • 33
  • 64
0

You could post some code, we're not supposed to guess it.

Anyway, you could create an object like this

let phoneBundle = {
    realPhone: '123-123-1234',
    displayPhone: 'xxx-xxx-' + this.phoneBundle.realPhone.substr(-1, 4)
};