Angular 2 限制输入字段 [英] Angular 2 restrict input field

查看:22
本文介绍了Angular 2 限制输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was wondering if it's possible to restrict an input field to a certain format like for example as many digits as you want then "." and then 2 digits? That's basically an input for a price... And I don't want a simple validation like the pattern attribute. I want the user to not be able to make a false input.

推荐答案

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

you need use a directive. In the directive add a hotListener about input and check if match with the regExpr indicated. I make a directive mask some time ago. The directive in the stackblitz, with the edvertisment that the code is provide "as is" without warranty of any kind.

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

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

Be carefull, when you write "mask" in a string (or in the html). e.g. for a number width two decimals is:

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

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

(the must be writed as \, { as {, } as } ...)

这篇关于Angular 2 限制输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆