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; } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com
暂无评论...
更新日志
2024年09月20日
2024年09月20日
- 《十年经典成名好歌 高品质最佳音乐 2CD》[WAV/分轨][1GB]
- 《8个男人的故事 2CD》[WAV/分轨][1GB]
- 《粤语超白金 百听不厌的经典金曲 2CD》[WAV/分轨][1.3GB]
- 群星.1994-全世界精丫华星】【WAV+CUE】
- 杜德伟.1997-知.解2CD【滚石】【WAV+CUE】
- 群星.2022-一不小心喵上你原声大碟【TME影音】【FLAC分轨】
- 《战锤40K星际战士2》卡在正在加入服务器解决方法
- 《勇者斗恶龙怪物仙境3》玩法内容介绍
- 《幸福工厂》无限报错解决方法
- 交错战线原始交易所推荐角色一览
- 战锤40K星际战士2战术职业介绍|战术职业技能效果一览
- 战锤40K星际战士2突击职业介绍|突击职业技能效果一览
- [妙音金曲]群星《悲情咖啡屋》(黑胶)2CD[DTS-WAV]
- 阿兰·达瓦卓玛《A-Lan阿兰唯美歌姬》2CD[DTS-WAV]
- 【小提琴】陈立新《思乡曲》2004[FLAC+CUE]