最近在寫一個表單,有些輸入框只能輸入數字,單又不想每次寫表單的時候,都要去驗證輸入的是不是數字,
那么就想到直接限制只能輸入數字,通過指令實現
這里需要注意的是,不只更改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 />