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.
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
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
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