ER.*_*ARI 5 validation input typescript angular
我在html页面上有许多输入框.我想限制用户输入2位小数后的任何数字.
目前尝试应用html 5输入Step ="0.00"但不起作用.
任何打字稿解决方案也都可以
我使用@pipe得到了解决方案
import { Directive,Input,Inject, HostListener, ElementRef, OnInit } from "@angular/core";
const PADDING = "000000";
@Pipe({ name: "CurrencyPipe" })
export class CurrencyPipe implements PipeTransform {
transform(value: any, args: string[]): any {
var clean = value.replace(/[^-0-9\.]/g, '');
var negativeCheck = clean.split('-');
var decimalCheck = clean.split('.');
if (negativeCheck[1] != undefined) {
negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
clean = negativeCheck[0] + '-' + negativeCheck[1];
if (negativeCheck[0].length > 0) {
clean = negativeCheck[0];
}
}
if (decimalCheck[1] != undefined) {
decimalCheck[1] = decimalCheck[1].slice(0, 2);
clean = decimalCheck[0] + '.' + decimalCheck[1];
}
return clean;
}
parse(value: string, fractionSize: number = 2): string {
var clean = value.replace(/[^-0-9\.]/g, '');
var negativeCheck = clean.split('-');
var decimalCheck = clean.split('.');
if (negativeCheck[1] != undefined) {
negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
clean = negativeCheck[0] + '-' + negativeCheck[1];
if (negativeCheck[0].length > 0) {
clean = negativeCheck[0];
}
}
if (decimalCheck[1] != undefined) {
decimalCheck[1] = decimalCheck[1].slice(0, 2);
clean = decimalCheck[0] + '.' + decimalCheck[1];
}
return clean;
}
}
Run Code Online (Sandbox Code Playgroud)
和 Pipe Extends 在我的指令中。
import { Directive, Input, Inject, HostListener, OnChanges, ElementRef, Renderer, AfterViewInit, OnInit } from "@angular/core";
import { CurrencyPipe } from '../../shared/pipe/orderby';
@Directive({ selector: "[CurrencyFormatter]" })
export class CurrencyFormatterDirective {
private el: HTMLInputElement;
constructor(
private elementRef: ElementRef,
private currencyPipe: CurrencyPipe
) {
this.el = this.elementRef.nativeElement;
}
ngOnInit() {
this.el.value = this.currencyPipe.parse(this.el.value);
}
@HostListener("focus", ["$event.target.value"])
onFocus(value) {
this.el.value = this.currencyPipe.parse(value); // opossite of transform
}
@HostListener("blur", ["$event.target.value"])
onBlur(value) {
this.el.value = this.currencyPipe.parse(value);
}
@HostListener("keyup", ["$event.target.value"])
onKeyUp(value) {
this.el.value = this.currencyPipe.parse(value);
}
}
Run Code Online (Sandbox Code Playgroud)
组件上的导入指令
import { CurrencyFormatterDirective } from '../../shared/directive/showOnRowHover';
import { CurrencyPipe } from '../../shared/pipe/orderby';
providers: [CurrencyPipe,
CurrencyFormatterDirective]
Run Code Online (Sandbox Code Playgroud)
和你的 html 输入指令
<input type="text" [(ngModel)]="invoiceDetail.InvoiceAmount" class="form-control" placeholder="Enter invoice amount"
CurrencyFormatter>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11965 次 |
| 最近记录: |