angular2 通过指令限制输入
2016-09-20 12:10
375 查看
最近在写一个表单,有些输入框只能输入数字,单又不想每次写表单的时候,都要去验证输入的是不是数字,
那么就想到直接限制只能输入数字,通过指令实现
这里需要注意的是,不只更改DOM的值,如果input为数据绑定的值,需要更新绑定值,
所以需要引入NgModel,通过viewToModelUpdate,来更新绑定值
引用方式:
html代码
那么就想到直接限制只能输入数字,通过指令实现
这里需要注意的是,不只更改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 />
相关文章推荐
- 通过正则表达式的进行输入限制的TextWatcher
- 编辑框输入限制可以通过键值来完成
- 限制你的指令只能通过特定的方式来调用
- angular2限制键盘响应,如:只接收数字键盘输入
- Flex中如何通过maxChars属性,限制TextArea控件中允许输入的字数
- JS通过正则限制 input 输入框只能输入整数、小数(金额或者现金)
- javascript 限制输入和粘贴 IE和火狐2.x、火狐3.x下测试通过
- Java简单输入&通过控制台输入相关指令,输出System类, RunTime类相关方法返回信息
- javascript 限制输入和粘贴(IE,firefox测试通过)
- javascript 限制输入和粘贴(IE和火狐3.x下测试通过)
- JS通过正则限制 input 输入框只能输入整数、小数(金额或者现金)
- 如何通过指令输入来启动安卓应用程序
- 通过javascript输入超过长度限制的密码
- JS通过正则限制 input 输入框只能输入整数、小数(金额或者现金) 两位小数
- JS通过正则限制 input 输入框只能输入整数、小数(金额或者现金)
- 最近装了windows 7也重装了vs2008,发现有90天试用限制。无法像xp下通过“控制面板”卸载的方法重新输入序列号破解了。
- 通过一行代码搞定UITextField的输入格式限制
- 通过输入框中字符串的像素长度限制输入文字长度
- 通过摇一摇功能 取消撤销键导致的 限制内容输入的崩溃问题 (关闭撤销功能)