第一次输入符号后输入失去焦点

时间:2019-08-12 12:12:40

标签: javascript html angular typescript

我有授权组件,用户可以使用其电话号码登录。还有一个问题,即输入一个符号(与字母或数字无关)input后失去焦点,用户需要再次单击它才能进一步输入。
UPD:忘记提及有3个输入。开始时会有第一个输入,当它为空时。在输入第一个数字后,将根据所在国家/地区的用户将其替换为第二个或第三个输入。对于某些国家/地区,它将被带有+7前缀的输入替换,对于另一个具有+9前缀的输入
html:

<input [(ngModel)]="phone"
             *ngIf="isPhoneEmpty()"
             class="phone-input m-b-50"
             id="phone-input"
             type="text"
             name="phone"
             minlength=18
             placeholder="Phone number"
             required>

    <input [(ngModel)]="phone"
             *ngIf="checkCountry() && !isPhoneEmpty()"
             class="phone-input m-b-50"
           id="phone-input"
             type="text"
             name="phone"
             minlength=18
             placeholder="Phone number"
             prefix="+7"
             mask=" (000) 000-00-00"
           autofocus
             required>

      <input [(ngModel)]="phone"
             *ngIf="!checkCountry() && !isPhoneEmpty()"
             class="phone-input m-b-50"
             id="phone-input"
             type="text"
             name="phone"
             placeholder="PhoneNumber"
             prefix="+996"
             mask=" (000) 000-000"
             autofocus
             required>

组件:

import { HostListener} from '@angular/core';
phone: string;

checkCountry() {
    return this.currentCountry.name === this.countryList[0].name;
  }
isPhoneEmpty() {
    return this.phone === '';
  }

@HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {

    const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

    if (numbers.indexOf(event.key) !== -1) {
     this._documentRef.getElementById('phone-input').focus();
    }
  }

2 个答案:

答案 0 :(得分:1)

问题是您有3个输入,并用* ngIf在这3个输入之间切换。当电话为空时,您会显示第一个输入,并且键入内容后,第一个输入的* ngIf值将为false,然后第一个输入将不呈现,而第二个输入将呈现,这就是为什么您输掉将重点放在第一个输入上。

我建议您只有一个输入字段,为什么需要三个输入字段?

答案 1 :(得分:0)

您怎么知道电话号码来自哪个国家。仅从第一个数字开始?还是用户已经向您提供了该信息?

如果您已经掌握了信息,请使用该信息在页面加载时显示所需输入,而不是在用户开始键入时显示所需输入。现在,第一次按键后输入发生变化,导致焦点丢失。