Home > database >  How to display a comma only in an input?
How to display a comma only in an input?

Time:05-25

In the input HTML, currently, the user can enter multiple commas, I would like to reduce the number of commas by 1. I d'ont know how to make this?

For example: The user cannot enter 20......01 but only 20.01

app.component.html

<input notdot maxlength="5" [(ngModel)]="value" />

app.component.ts

export class AppComponent  {
  value
}

app.module.ts

@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [AppComponent, NotDotDirective],
  bootstrap: [AppComponent],
})
export class AppModule {}

dot.directive.ts

import { Directive,Injector,HostListener,Optional,Host } from '@angular/core';
import {NgControl} from '@angular/forms'
@Directive({
  selector: '[notdot]'
})
export class NotDotDirective {

  constructor(@Optional() @Host()private control:NgControl) {}
  @HostListener('input', ['$event'])
  change($event) {

    const item = $event.target
    const value = item.value;
    const pos = item.selectionStart; //get the position of the cursor

    const matchValue = value.replace(/,/g, '.')
    if (matchValue!=value)
    {
      if (this.control)
        this.control.control.setValue(matchValue, { emit: false });

      item.value = matchValue;
      item.selectionStart = item.selectionEnd = pos; //recover the position
    }
  }
}

Here is a reproduction -> here. If you have a solution, I am really interested.

Thank you very much for your help.

CodePudding user response:

On your directive you can change line 20 with:

const matchValue = value.replace(/,/g, '.').replace(/\.\./, '.');

You are replacing comma with dots and if you insert more than one dot, it replaces the input with just only one

CodePudding user response:

Menier, then use a "mask" directive (but you check againts value.replace(/,/g, '.'); . Some like

regExpr = new RegExp('^([1-9]\\d*|0)(\\.)?\\d*$');

@HostListener('input', ['$event'])
  change($event) {

    let item = $event.target
    let value = item.value;
    let pos = item.selectionStart;
    let matchvalue = value.replace(/,/g, '.');
    let noMatch: boolean = (value && !(this.regExpr.test(matchvalue)));
    if (noMatch) {
      item.selectionStart = item.selectionEnd = pos - 1;
      if (item.value.length < this._oldvalue.length && pos == 0)
        pos = 2;
      if (this.control)
        this.control.control.setValue(this._oldvalue, { emit: false });

      item.value = this._oldvalue;
      item.selectionStart = item.selectionEnd = pos - 1;
    }
    else
    {
      //we check here if matchValue!=value

      if (matchvalue!=value)
      {
        item.value = matchvalue;
        item.selectionStart = item.selectionEnd = pos;
      }

      this._oldvalue = matchvalue;

    }

  }
  • Related