Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Field Masking

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.

like image 964
Lucifer Avatar asked Jul 04 '17 09:07

Lucifer


2 Answers

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

like image 82
Faly Avatar answered Sep 18 '22 12:09

Faly


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

like image 37
Aakash Thakur Avatar answered Sep 20 '22 12:09

Aakash Thakur