angularinputNumber指令输入框只能输入数字的示例分析-创新互联

小编给大家分享一下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指令输入框只能输入数字的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!

本文题目:angularinputNumber指令输入框只能输入数字的示例分析-创新互联
标题URL:https://www.cdcxhl.com/article36/csppsg.html

成都网站建设公司_创新互联,为您提供网站策划网站制作微信小程序静态网站全网营销推广品牌网站设计

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

营销型网站建设