首页 > 其他 > 详细

angular2 通过指令限制输入

时间:2016-09-20 13:34:17      阅读:451      评论:0      收藏:0      [点我收藏+]

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

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

 

这里需要注意的是,不只更改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;
    }
  }

}

 

angular2 通过指令限制输入

原文:http://www.cnblogs.com/liuyt/p/5888318.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!