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;
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
BETTER62881837