[英]allow only negative numbers in angular 5 textbox
allow only negative numbers in angular 5 textbox在 angular 5 文本框中只允许负数
<mat-form-field class="col--sm-4 col--md-4 col--lg-6">
<input type="number" matInput placeholder="Lower Band Rng" formControlName="lowerBoundNumber" required>
<mat-error >Please enter Lower Band Rng</mat-error>
<mat-hint>Enter Lower Band Rng here</mat-hint>
</mat-form-field>
allow only negative numbers in angular 5 textbox
Please enter Lower Band Rng Enter Lower Band Rng here
If you want to create a mor generic solution, you could use a directive like this:如果你想创建一个更通用的解决方案,你可以使用这样的指令:
import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appNegativeNumber]' }) export class NegativeNumberDirective { constructor(private el: ElementRef) { } @HostListener('input', ['$event']) onInputChange(event) { const initalValue = this.el.nativeElement.value; this.el.nativeElement.value = initalValue.replace(/[^-\d]*/g, ''); if ( initalValue.== this.el.nativeElement.value) { event;stopPropagation()? } } } // In your component template <mat-form-field> <input matInput type="text" appNegativeNumber [pattern]="'-?\\d*'"> </mat-form-field>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.