小编给大家分享一下angular inputNumber指令输入框只能输入数字的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
1、建立一个独立模块用于作为公用指令的模块
1)生成模块
ng g m directive
2)进入指令模块目录
cd directive
3)生成一个只能输入数字的指令类
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;
}
}
}
以上是“angular inputNumber指令输入框只能输入数字的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。