首页 > 解决方案 > 如何省略 0 和负数,但用户可以在角材料中输入例如 10

问题描述

所以我有一个 Angular 8 应用程序,我正在使用 Material Angular 库。我有一个数字字段。但我想省略用户输入负数和数字 0。我找到了解决方案。但是现在用户甚至不能输入例如数字 10 - 在这种情况下是一个有效数字。

我有这个:

<ng-container>
                <mat-form-field>
                  <input
                    matInput
                    type="number"
                    formControlName="maxAllowedToScan"
                    placeholder="Max allowed scanned"
                    i18n-placeholder
                    onkeypress="return event.charCode >= 49"
                    min="1"
                  />
                  <mat-error *ngIf="qrForm.get('maxAllowedToScan').invalid && qrForm.get('maxAllowedToScan').dirty">
                    {{ errors.maxAllowedToScan }}
                  </mat-error>
                </mat-form-field>
              </ng-container>

这就是我在 ts 文件中的内容:

 this.qrForm = this.fb.group({
      qrcode: [this.definition.qrcode, Validators.required],
      title: [this.definition.title, Validators.required],
      description: [this.definition.description, Validators.required],
      maxAllowedToScan: [
        this.definition.maxAllowedToScan // ,
        // this.requiredIfScanFrequencyTypeIsNotNone( scanFrequencyTypeControl, 'maxAllowedToScan' )
      ],

所以我的问题是:如何改善这一点?

谢谢

但如果我这样做:

<ng-container>
                <mat-form-field>
                  <input
                    matInput
                    type="number"
                    formControlName="maxAllowedToScan"
                    placeholder="Max allowed scanned"
                    i18n-placeholder
                    onkeypress="return event.charCode >= 49"
                  />
                  <mat-error *ngIf="qrForm.get('maxAllowedToScan').invalid && qrForm.get('maxAllowedToScan').dirty">
                    {{ errors.maxAllowedToScan }}
                  </mat-error>
                </mat-form-field>
              </ng-container>

那么用户仍然无法输入例如数字 10。

我试过这样:

 <ng-container>
                <mat-form-field>
                  <input
                    matInput
                    type="number"
                    formControlName="maxAllowedToScan"
                    placeholder="Max allowed scanned"
                    i18n-placeholder
                    onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57"
                    (change) = 'preventLeadingZero()'

                  />

标签: javascriptangulartypescriptangular-material

解决方案


您可以编写一个简单的函数来处理(keypress)事件,它将检查输入的长度和输入的 charCode 并防止输入前导零,例如:

function preventLeadingZero(event) {
  const input = event.target.value;


  if (input.length === 0 && event.which === 48) {
    event.preventDefault();
  }
}

推荐阅读