Input中的Angular4掩码字符,不更改其值

时间:2017-12-02 18:34:33

标签: angular

如何在不改变实际值的情况下屏蔽Angular 4中除最后四个之外的所有字符(即show *)?

例如:数字应该在输入文本框中看起来像*** 1234,值应该是7671234。

2 个答案:

答案 0 :(得分:1)

使用指令

@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);
  }
}

答案 1 :(得分:1)

如果你想在TemplateDriveForm中使用该指令,你必须添加AfterViewChecked事件,因为在ngOnInit中我们无法获得&#34;真实值&#34;

@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();
    }
 }
 .....