Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display a comma only in an input?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading