Angular 2 限制输入字段

Kai*_*Kai 0 input restriction angular

我想知道是否可以将输入字段限制为某种格式,例如您想要的尽可能多的数字然后“。” 然后是2位数?这基本上是价格的输入......而且我不想要像模式属性这样的简单验证。我希望用户不能进行错误输入。

Eli*_*seo 5

你需要使用一个指令。在指令中添加一个关于输入的 hotListener 并检查是否与指示的 regExpr 匹配。我前段时间做了一个指令掩码。stackblitz 中的指令,并声明代码“按原样”提供,没有任何形式的保证。

@Directive({
  selector: '[mask]'
})
export class MaskDirective {
  @Input()
  set mask(value) {
    this.regExpr = new RegExp(value);
  }

  private _oldvalue: string = "";
  private regExpr: any;
  private control: NgControl;
  constructor(injector: Injector) {
    //this make sure that not error if not applied to a NgControl
    try {
      this.control = injector.get(NgControl)
    }
    catch (e) {
    }
  }
  @HostListener('input', ['$event'])
  change($event) {

    let item = $event.target
    let value = item.value;
    let pos = item.selectionStart; //get the position of the cursor
    let matchvalue = value;
    let noMatch: boolean = (value && !(this.regExpr.test(matchvalue)));
    if (noMatch) {
      item.selectionStart = item.selectionEnd = pos - 1;
      if (item.value.length < this._oldvalue.length && pos == 0)
        pos = 2;
      if (this.control)
        this.control.control.setValue(this._oldvalue, { emit: false });

      item.value = this._oldvalue;
      item.selectionStart = item.selectionEnd = pos - 1; //recover the position
    }
    else
      this._oldvalue = value;
  }
}
Run Code Online (Sandbox Code Playgroud)

当你在字符串(或 html)中写“掩码”时要小心。例如,对于数字宽度两位小数是:

[mask]="'^[+-]?([1-9]\\d*|0)?(\\.\\d\{0,2\})?$'"
Run Code Online (Sandbox Code Playgroud)

(\ 必须写成 \\, { as \{, } as \} ...)