angular inputNumber指令輸入框只能輸入數(shù)字的實現(xiàn)
1、建立一個獨立模塊用于作為公用指令的模塊
1)生成模塊
ng g m directive
2)進入指令模塊目錄
cd directive
3)生成一個只能輸入數(shù)字的指令類
ng g d numberinput
4)指令模塊directive.module.ts代碼如下
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NumberinputDirective } from './numberinput.directive';
@NgModule({
imports: [
CommonModule
],
declarations: [NumberinputDirective],
exports:[ // 使引用該模塊的類可以使用該指令
NumberinputDirective
]
})
export class DirectiveModule { }
5)指令類numberinput.directive.ts代碼如下
@Directive({
selector: 'input[numberInput]'
})
export class NumberInputDirective {
// tslint:disable-next-line: no-input-rename
@Input('numberInput') numberType: string;
constructor(private el: ElementRef) {}
@HostListener('input', ['$event.target.value'])
onChange(value: string): void {
if (this.numberType.length < 1) {
this.updateIntegerValue(value);
} else {
this.el.nativeElement.value = value.replace(/[^\d.]/g, '');
}
}
@HostListener('blur', ['$event.target.value']) onBlur(value: number): void {
if (this.numberType.length >= 1) {
this.updateFloatValue(value);
}
}
updateIntegerValue(value: string): void {
this.el.nativeElement.value = value.replace(/[^\d]/g, '');
}
updateFloatValue(floatValue: number): void {
const value = String(floatValue);
const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/.test(value);
const numBegin = /^\d/.test(value);
const numEnd = /\d$/.test(value);
if (reg && numBegin && numEnd) {
this.el.nativeElement.value = value;
} else {
this.el.nativeElement.value = 0;
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
angular.js + require.js構(gòu)建模塊化單頁面應(yīng)用的方法步驟
這篇文章主要給大家介紹了關(guān)于利用angular.js + require.js構(gòu)建模塊化單頁面應(yīng)用的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。2017-07-07
angularjs項目的頁面跳轉(zhuǎn)如何實現(xiàn)(5種方法)
本篇文章主要介紹了詳解angularjs項目的頁面跳轉(zhuǎn)如何實現(xiàn) ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
淺談angularjs $http提交數(shù)據(jù)探索
這篇文章主要介紹了淺談angularjs $http提交數(shù)據(jù)探索,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-01-01
angularJs select綁定的model取不到值的解決方法
今天小編就為大家分享一篇angularJs select綁定的model取不到值的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
詳解在 Angular 項目中添加 clean-blog 模板
本篇文章主要介紹了詳解在 Angular 項目中添加 clean-blog 模板,非常具有實用價值,需要的朋友可以參考下2017-07-07

