Search code examples
angularmaskmat-input

How to mask all characters except last 3 characters on a string display only


Hi I am working in Angular and in one of the field which is phone number ,I want to mask the string on HTML view only except the last 3 characters. How can I do that ?

Example: - 1212121212 as XXXXXXX212 or *******212

Note: - Only in view I need to show masked. The field is editable and I am patching pre defined value. Once I input new value then mask must not show

<input matInput placeholder='{{"PhoneNumber" | translate}}' formControlName="mobilenumber"
            class="form-control" numbersOnly maxlength="10" minlength="10" required autocomplete="off"
            pattern="[6789][0-9]{9}" title="Please enter valid phone number" inputmode="numeric">

Solution

  • To use in a FormControl you need know when is focus and when not then you can use some like

     [ngModel]="condition?(yourFormControl.value|yourpipe):
                yourFormControl.value"
     (ngModelChange)="! condition && yourFormControl.setValue($event)"
    

    Imagine you has a variable "caracteres" and a FormGroup

      caracteres:number=3;
      form=new FormGroup({
        name:new FormControl()
        mobilenumber:new FormControl(),
        
      })
    

    You can to have some like

    <form [formGroup]="form">
         <input matInput 
                (focus)="caracteres=0" 
                (blur)="caracteres=3"  
                [ngModel]="caracteres?(form.get('mobilenumber').value|hideChars):
                           form.get('mobilenumber').value" 
                (ngModelChange)="!caracteres && form.get('mobilenumber').setValue($event)"
                [ngModelOptions]="{standalone:true}"
                class="form-control">
    
         <!--see that the rest of your input are in the way-->
         <input formControlName="name"/>
    </form>