简体   繁体   中英

allow only negative numbers in angular 5 textbox

allow only negative numbers in angular 5 textbox

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM