skip to Main Content

I have an input field where the requirement is that it has 0 initially set on change of value that 0 is removed and number is added but that 0 is removed only if key pressed by user is a number now the issue arises that when I do use a input event it take my value as sing quoted string as ‘8’ i had used replace method but what if I press backspace also on focus out it adds a .00 to a number if its there but i am also found a issue when my number is initially 0 and i press a nonnumberic value it makes my number set ” and also on backspace keypress it should allow backspace and remove zero but should not give an error when I remove the last not 0 number after typing something and do a backspace it gives error as Cannot read properties of null (reading ‘replace’) that is also case so its a mix of various cases

<input type="text" class="someclass" [readOnly]="isView || isEdit" placeholder=""
                        formControlName="somename" mask="separator.2" thousandSeparator="," (input)="removeZeroOnKeydown($event)"
                        (focusout)="onFixedAmount('somename')" separatorLimit="99999999999999">
                     <label class="label">Some Label$</label>

   removeZeroOnKeydown(event: InputEvent) {
    let inputElement = event.target as HTMLInputElement;

    //Get FormControl Name on keydown
    let controlName = inputElement.getAttribute('formControlName');
    
    if (!controlName) return;

    let control = this.myformname.controls[controlName];

    //Check Formcontrol input field value
    let controlValue = control.value;

    // If the input field only contains "0", replace it with the input data
    if (controlValue == 0 || controlValue == '') {

    //Get the keypressed value
    let inputData = (event as InputEvent).data;

    //let numberValue = inputData.replace(/'/g, "");
    
    if (inputData && /^d$/.test(inputData.replace(/'/g, ""))) {

      //Set value of keypressed
      control.setValue(inputData);
    }
    else{
      if(controlValue == 0 && controlValue){
      control.setValue(0);
      }
      else if(!/^d$/.test(inputData.replace(/'/g, "")) && controlValue != 0) {
        control.setValue('');
      }
    }
  }
}

 onFixedAmount(FormControlName) {
    let amount = this.myformname.controls[FormControlName].value;
    if (amount) {
      this.myformname.controls[FormControlName].setValue(amount ? Number(amount).toFixed(2) : 0);
    }
  }

2

Answers


  1. Chosen as BEST ANSWER

    I just twerked my condition a bit for else like

    //Check if numput data is not numeric and also control value is not 0 so perform backspace

      else if(!/^d$/.test(inputData) && controlValue != 0) {
        control.setValue('');
      }
    

  2. This will allow user to only type numbers, but additionally if input already contains numeric value and user tries to add string or something else than number, value will be set to previus valid one

    When User removes last number, input value will be set back to 0.
    when User writes first number, 0 will be removed

      <form class="form" [formGroup]="form">
        <input type="text" placeholder="test " formControlName="testname" />
      </form>
    
    
    
      private $destroyRef = new Subject<void>();
    
      form = new FormGroup({
        testname: new FormControl<number>({ value: 0, disabled: false }),
      });
    
      private $destroyRef = new Subject<void>();
    
      form = new FormGroup({
        testname: new FormControl<number | null>({ value: 0, disabled: false }),
      });
    
      ngOnInit(): void {
        this.form.controls.testname.valueChanges
          .pipe(
            takeUntil(this.$destroyRef),
            startWith({ oldVal: 0, newVal: 0 }),
            distinctUntilChanged(),
            pairwise(),
            map(([oldVal, newVal]) => ({ oldVal, newVal }))
          )
          .subscribe({
            next: (res) => {
              let regexp = /^d+$/;
              this.form.controls.testname.setValue(
                !regexp.test(String(res.newVal)) ? typeof res.oldVal === 'object'
                    ? null
                    : res.oldVal === res.oldVal && String(res.oldVal).length === 1
                    ? 0
                    : Number(res.oldVal)
                  : Number(res.newVal)
              );
            },
          });
      }
    
      ngOnDestroy() {
        this.$destroyRef.next();
        this.$destroyRef.complete();
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search