allow only negative numbers in angular 5 textbox

118 Views Asked by At

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
1

There are 1 best solutions below

0
Zsolt Balint On

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>