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.