0

How can I mask all characters (i.e. show *) in input except last four in Angular 4 without changing the actual value?

For example: number should look like ***1234 inside input textbox and the value should be 7671234.

2 Answers 2

2

Use a directive

@Directive({
  selector: '[stringHide]'
})
export class StringDirective implements OnInit {
  private value: any;  //the variable where we save the "true value"
  private element: HTMLInputElement
  constructor(private el: ElementRef, private form: ControlContainer) {
    this.element = el.nativeElement;
  }
  ngOnInit() { //It's necesary use OnInit, otherwise the first time not formtted
    this.value = this.element.value;
    this.formatValue();
  }
  @HostListener('input') onChange() {  //when a change happens save the value in a variable
    this.value = this.element.value;   
  }
  @HostListener('blur') onBlur() { //when lost the focus call format function
    this.formatValue();
  }
  @HostListener('focus') onFocus() { //when get the focus recover the true value
    this.element.value = this.value;
  }
  formatValue() { //here, change the apperance of the input
                  //I choose that if the value.length>14 only show 10 "*"
    let len=this.element.value.length;
    this.element.value = (len <= 4) ? this.element.value:
                         (len>14)? "**********"+this.element.value.substr(len - 4):
                               "**************".substring(0,len-4)+this.element.value.substr(len - 4);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Will this work if you move the cursor in the input box?
The directive works fine in a Reactive Form. there is a problem when this directive it's used with template driven forms. If I'll resolve I'll change the code
What If I need an input of type="number" (for reactive forms to perform min max validations but want to show the number 1234.56 as 1.234,56 (my locale inverts "." and "," separators) I tried to use decimalPipe.transform, but the type of the input clears the box.
1

If you want to use the directive in a TemplateDriveForm you must add AfterViewChecked event because in ngOnInit we cannot get the "real value"

@Directive({
  selector: '[stringHide]'
})
export class StringDirective implements OnInit,AfterViewChecked { //<--AddAfterViewChecked
private value: any; 
private initialized:boolean; //<--add a new variable
....
//Add ngAfterViewCheckecd 
ngAfterViewChecked()
{
   if (this.element.value && !this.initialized)
   {
      this.initialized=true;
      this.value = this.element.value;
      this.formatValue();
    }
 }
 .....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.