【问题标题】:why keypress event is not worked in two input?为什么按键事件在两个输入中不起作用?
【发布时间】:2021-09-30 05:55:19
【问题描述】:

我使用有角度的离子框架。我写了这样的HTML

<div><ion-input type="text" id="phoneNumber" [(ngModel)]="phoneNumber" (keypress)="phoneNumericCheck($event)" [disabled]="isSendParamDisabled" maxlength="11" placeholder="{{ 'TEXT.INPUT_FIELD_PHONE_NUMBER' | translate }}"></ion-input></div>
<ion-input [(ngModel)]="authNumber" type="text" id="Auth" maxlength="6" (keypress)="authNumericCheck($event)" placeholder="{{ 'TEXT.INPUT_FIELD_AUTH_NUMBER' | translate }}"></ion-input>

我在两个按键事件中使用了不同的功能,但它可以工作 authNumber 但 phoneNumber 不能。

如果我只使用一个按键事件,效果很好。我不知道为什么。

事件函数内容相同

public phoneNumericCheck(event: any) {
    const pattern = /[0-9.,]/;
    let value = String.fromCharCode(event.charCode);
    let success = pattern.test(value);
    if(!success) {
      event.preventDefault();
      this.alertAboutOnlyNumeric();
    }
  }

而且这个事件有时不起作用...我不知道为什么

【问题讨论】:

    标签: angular typescript ionic-framework events keypress


    【解决方案1】:

    我可以建议对电话输入使用不同的方法吗?

    <ion-input type="tel" autocomplete formControlName="phone"></ion-input>
    
    this.registrationForm = this.fb.group({
      phone: ['', [Validators.required, Validators.pattern(PhoneNumberRegex)]],
    });
    

    对于PhoneNumberRegex,您可以使用特定的电话号码格式(如here)或直接使用^[0-9]*$

    【讨论】:

    • 我需要在输入不是数字时显示警报
    • @장호정 你可以通过检查formGroup.controls[controlName].invalid来做到这一点。确保在显示警报之前检查formGroup.controls[controlName].touched 是否为真,否则它将从一开始就显示警报。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    相关资源
    最近更新 更多