首页 > 解决方案 > 如何屏蔽输入文本框中输入的每三个数字。单击提交按钮时,必须显示原始的未屏蔽值

问题描述

现在我只能在模糊时屏蔽数字。我需要在输入时屏蔽它们。单击提交按钮时,需要显示原始输入的值。我在这里创建了它:https ://stackblitz.com/edit/angular-gnkvpt?file=src/app/app.component.ts

https://angular-gnkvpt.stackblitz.io

标签: angularmasking

解决方案


您需要使用几乎两个变量,一个用于存储值,一个用于显示它

  valueNoMask = '123456';
  value = MaskTransfor(this.valueNoMask, this.showMask);

然后,我去劈[(ngModel)]

<input #input
  type="text"
  name="value"
  [ngModel]="value"
  (ngModelChange)="change($event,input)"
/>

看到我传递给函数,还有 $event,使用模板引用变量的“HTML 输入” -this #input-

这使得光标不仅可以轻松放置在输入的末尾,还可以轻松放置在它所在的位置。

但首先我去简化你的管道。我喜欢(正如 Angular 所做的那样)创建一个可以在管道中导出和使用的函数

export function MaskTransfor(value: string, showMask: boolean): string {
  if (showMask)
    return [...value].map((x, index) => ((index + 1) % 3 ? x : '*')).join('');

  return value;
}

@Pipe({
  name: 'mask',
})
export class MaskPipe implements PipeTransform {
  transform(value: string, showMask: boolean): string {
    return MaskTransfor(value, showMask);
  }
}

看到我们总是想在每次有用时重复“某事”使用余数运算符

因此,您可以使用 .ts 中的函数,而无需创建对象 MaskPipe。

功能变化变得像

  change(value: string, el: any) {
    //get where the cursor is
    const selectionStart = el.selectionStart;

    //find the parts equals the "value" -the actual value of the input
    //and this.value, the value "before". So, imagine 
    //this.value="12345" (
    //and value="123a45"
    //I want get three elements: 123, a, 45

    let end = 0;
    let start = 0;
    for (let i = 0; i < value.length; i++) {
      if (value.slice(0, i) == this.value.slice(0, i)) start = i;
      if (value.slice(-i) == this.value.slice(-i)) end = -i;
    }

    
    if (end == 0 || start == 0) //if I changed at first or at end
      this.valueNoMask = this.valueNoMask.slice(0, start) + value.slice(start);
    else //else
      this.valueNoMask =
        this.valueNoMask.slice(0, start) +
        value.slice(start, end) +
        this.valueNoMask.slice(end);

    //equal the value to the value transform
    this.value = MaskTransfor(this.valueNoMask, this.showMask);
    
    //place the cursor in the position
    el.selectionStart = el.selectionEnd = selectionStart;
  }

你可以在这个 stackblitz中看到


推荐阅读