angularinputNumber指令輸入框只能輸入數(shù)字的示例分析-創(chuàng)新互聯(lián)

小編給大家分享一下angular inputNumber指令輸入框只能輸入數(shù)字的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

成都創(chuàng)新互聯(lián)堅持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都做網(wǎng)站、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時代的泰來網(wǎng)站設(shè)計、移動媒體設(shè)計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!

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;
  }
 }
}

以上是“angular inputNumber指令輸入框只能輸入數(shù)字的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

本文題目:angularinputNumber指令輸入框只能輸入數(shù)字的示例分析-創(chuàng)新互聯(lián)
標題URL:http://muchs.cn/article36/csppsg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃網(wǎng)站制作、微信小程序、靜態(tài)網(wǎng)站全網(wǎng)營銷推廣、品牌網(wǎng)站設(shè)計

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

營銷型網(wǎng)站建設(shè)