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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Angularjs 動態(tài)改變title標題(兼容ios)
這篇文章主要介紹了 Angularjs 動態(tài)改變title標題(兼容ios)的相關(guān)資料,需要的朋友可以參考下2016-12-12在angularJs中進行數(shù)據(jù)遍歷的2種方法
今天小編就為大家分享一篇在angularJs中進行數(shù)據(jù)遍歷的2種方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10AngularJS入門教程之與服務(wù)器(Ajax)交互操作示例【附完整demo源碼下載】
這篇文章主要介紹了AngularJS與服務(wù)器Ajax交互操作的方法,可實現(xiàn)post傳輸數(shù)據(jù)的功能,并附帶完整的demo源碼供讀者下載參考,源碼中還包含了前面章節(jié)的示例文件,需要的朋友可以參考下2016-11-11Angular.js中$apply()和$digest()的深入理解
相信大家都知道$digest()和$apply()是AngularJS中的兩個核心并且有時候容易引人誤解的部分。我們需要深入理解這兩者是如何運作的,從而才能理解AngularJS本身是如何運作的。本文的目的就是介紹$digest()和$apply()是如何確確實實的對你有用的。下面來一起看看吧。2016-10-10在 Angular6 中使用 HTTP 請求服務(wù)端數(shù)據(jù)的步驟詳解
本文分步驟給大家介紹了在 Angular6 中使用 HTTP 請求服務(wù)端數(shù)據(jù)的方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08Angularjs通過指令監(jiān)聽ng-repeat渲染完成后執(zhí)行腳本的方法
指令是angular的核心功能之一,用好了事半功倍,監(jiān)聽ng-repeat執(zhí)行狀態(tài)僅僅是它功能的冰山一角吧。下面這篇文章主要介紹了Angularjs通過指令監(jiān)聽ng-repeat渲染完成后執(zhí)行腳本的方法,需要的朋友可以參考下。2016-12-12