如何自动将逗号转换为点?

How to convert a comma to dot automatically?

当用户在 INPUT 中输入逗号时,我希望逗号自动转换为点号。可能吗?

<label>Number </label>
<input type="number" maxlength="5" />

这是复制品 -> Link

使用 Angular 表单控件会自动将其转换为正确的数字:

https://stackblitz.com/edit/angular-ivy-uewxfs?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts

<input> elements 类型的数字用于让用户输入数字。它们包括 built-in 验证以拒绝 non-numerical 个条目。

用户不能在INPUT中输入逗号,因此首先您必须将输入类型更改为文本。在 onkeyup 事件之后,您可以替换如下值:

<input type="text" onkeyup="this.value=this.value.replace(/,/g, '.');"/>

https://stackblitz.com/edit/angular-ivy-hc3mn8?file=src/app/app.component.html

你可以做这样的旧东西

创建指令

@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
    }
  }
}

并使用喜欢

<input notdot maxlength="5"/>

注意您也可以使用模板驱动的表单或 ReactiveForms

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

<input notdot [formControl]="control" maxlength="5"/>

您可以在this stackblitz

中看到