0

Here is my OnlyNumber directive it work fine in only number. I want that whenever the user puts 0 in input field it's converted into 1

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[OnlyNumber]'
})
export class OnlyNumber {

  constructor(private el: ElementRef) { }

  @Input() OnlyNumber: boolean;

  @HostListener('keydown', ['$event']) onKeyDown(event) {
    let e = <KeyboardEvent> event;
    console.log(e);
    if (this.OnlyNumber) {
      if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
        // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) ||
        // Allow: Ctrl+C
        (e.keyCode == 67 && e.ctrlKey === true) ||
        // Allow: Ctrl+X
        (e.keyCode == 88 && e.ctrlKey === true) ||
        // Allow: Numpad Number
        (e.keyCode >= 96 && e.keyCode <= 105) ||
        // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
          // let it happen, don't do anything
          return;
      }
      // Ensure that it is a number and stop the keypress
      if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
          e.preventDefault();
      }
    }
  }
}

This my html input fields:

<input OnlyNumber='true'  MaxNumber="9" type="text" [(ngModel)]='cart.selectedQty'
                                (ngModelChange)='calculateTotalPrice($event,cart,i)' class="mb-0" />

Please give me any solution.

Ling Vu
  • 4,740
  • 5
  • 24
  • 45
rajpoot rehan
  • 435
  • 5
  • 14
  • It _looks_ like you're trying to get a numbere which is bigger then 0, from that HTML snippet at least. Is that true? If yes, why not simply adding a `min` directive? – Zlatko Dec 13 '19 at 08:25

1 Answers1

4

You could simply replace every '0' to '1' after every keydown event, right? Like:

@HostListener('keyup', ['$event']) onKeyUp(event) {
    this.el.nativeElement.value= this.el.nativeElement.value.replace('0', '1');
}

Demo for your reference: https://stackblitz.com/edit/angular-fndxsq

My source for keyup: How can I get jquery .val() AFTER keypress event?

For more information about replace: https://www.w3schools.com/jsref/jsref_replace.asp

Ling Vu
  • 4,740
  • 5
  • 24
  • 45
  • Changes: I changed this code from `keydown` to `keyup` since it needs to be changed AFTER keypress, if you wondered. – Ling Vu Dec 13 '19 at 08:26
  • its work fine but i want add one more condition If a user inter value in input and clear it, then Still show input 1 – rajpoot rehan Dec 13 '19 at 08:38
  • For that you can use the `onchange` event and react if it is empty. I think it is pretty straight forward. – Ling Vu Dec 13 '19 at 08:40