angular2 通过指令限制输入

最近在写一个表单,有些输入框只能输入数字,单又不想每次写表单的时候,都要去验证输入的是不是数字,

那么就想到直接限制只能输入数字,通过指令实现

这里需要注意的是,不只更改DOM的值,如果input为数据绑定的值,需要更新绑定值,

所以需要引入NgModel,通过viewToModelUpdate,来更新绑定值


import { Directive } from '@angular/core';
import { NgModel }   from '@angular/forms';

// 自定义指令
@Directive({
  selector: 'input[number]',
  host: {
    '(keypress)': 'onkeypress($event)',
    '(keyup)': 'onkeyup($event)'
  },
  inputs: ['maxValue'],
})

export class NumberInput {
  maxValue: number;

  constructor(public control: NgModel) {
  }

  onkeyup(event) {
    let input = event.target;
    if (input.value == "") {
      input.value = 0;
      this.control.viewToModelUpdate(0);
    }
    let newValue = parseInt(input.value);
    if (newValue > this.maxValue) {
      input.value = this.maxValue;
      this.control.viewToModelUpdate(this.maxValue);
    }
    else
    {
      input.value = newValue;
      this.control.viewToModelUpdate(newValue);
    }

  }

  onkeypress(event) {
    // 判断是否为数字
    let inputStr = String.fromCharCode(event.keyCode);
    if (!parseInt(inputStr)) {
      return false;
    }
  }

}

引用方式:

import {
  NumberInput
} from './directives';

@NgModule({
  declarations: [
    NumberInput
  ],
  imports: [
  ],
  providers: [
  ],
  exports: [
  ]
})

html代码

<input type="number" NumberInput />
原文地址:https://www.cnblogs.com/liuyt/p/5888318.html