我有一个场景,我应该在 Angular 2/4/5 中限制输入框保留 2 位小数。我应该为此编写指令吗?
示例:12.25、14524.21、12547896324.01
我们不应允许用户在完成两个小数值后输入额外的按键
最佳答案
- 在您的 HTML 文件中添加以下代码
<label>Enter value</label> <br/> <input type="text" name="test" placeholder="00.00" [(ngModel)]="textValue" appIsDecimal>
- 在 ts 文件中声明 textValue 变量。
- 然后通过以下命令创建指令
ng g d IsDecimalDirective
- 将该指令声明添加到模块中。
在 IsDecimalDirective 文件中写入以下代码
import { Directive, ElementRef, HostListener, Input, forwardRef, Attribute, AfterContentInit, OnChanges, OnDestroy } from '@angular/core'; import { NG_VALIDATORS, AbstractControl, ValidatorFn, Validator, FormControl, NgModel } from '@angular/forms'; @Directive({ selector: '[IsDecimal]' }) export class IsDecimalDirective { private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g); private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete']; constructor( private el: ElementRef ) { } @HostListener('keydown', ['$event']) onKeyDown(event: KeyboardEvent) { // Allow Backspace, tab, end, and home keys if (this.specialKeys.indexOf(event.key) !== -1) { return; } let current: string = this.el.nativeElement.value; const position = this.el.nativeElement.selectionStart; const next: string = [current.slice(0, position), event.key == 'Decimal' ? '.' : event.key, current.slice(position)].join(''); if (next && !String(next).match(this.regex)) { event.preventDefault(); } } }
- 这是 StackBits demo 的链接
关于angular - 如何在 Angular 2/4/5 中限制输入框保留 2 位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48317241/