输入标签中的焦点在通过 angular(8.x) 中的类方法更新其值后消失



我正在实施信用卡支付,我正在通过以下一些方法格式化它的no:

HTML

<div class="form-group" *ngFor="let formField of cardFields;let cardFieldIndex = index;">
<label class="form-label">{{formField.label}}</label>
<input class="form-input" type="text" [(ngModel)]="formField.val" [placeholder]="formField.label" (ngModelChange)="changeCardField(cardFieldIndex, $event)">
</div> 

app.payment.comcomponent.ts

changeCardField(index, ev) {
const formatFields = ({key}, val) => {
if (key === 'card_number') {
val = val.split(/[^0-9]/).join('');
return getCardType(val);
} 
return val.trim();
};
this.cardFields[index] = {...this.cardFields[index], ...formatFields(this.cardFields[index], this.cardFields[index].val)};
}

我尝试了多种方法

  1. 使用带setTimeout的反跳
  2. 使用$event.target.focus((
  3. [value]="formField.val"(keyup/change/ngModelChange)="changeCardField(cardFieldIndex, $event)"组合的直接更新字段

在所有情况下,输入元素的焦点都会消失。找不到摆脱困境的方法。

这导致我无法在输入字段中正确键入

我找到了一个解决方案(不是完美的解决方案(:

HTML

<div class="form-group" *ngFor="let formField of cardFields;let cardFieldIndex = index;">
<label class="form-label">{{formField.label}}</label>
<input class="form-input" type="text" #CardNumberInput [(ngModel)]="formField.val" [placeholder]="formField.label" (keydown)="changeCardField(cardFieldIndex, $event)">
</div>

添加了视图变量CardNumberInput

app.payment.comcomponent.ts

import {ViewChildren} from '@angular/core';
let commitTimer;
export class AppPaymentComponent {
...
@ViewChildren("CardNumberInput") cardNumberInput: QueryList<ElementRef>;
...
changeCardField(index, ev) {
clearTimeout(commitTimer);
const formatFields = ({key}, val) => {
if (key === 'card_number') {
val = val.split(/[^0-9]/).join('');
return getCardType(val);
} else if (key === 'expiry_date') {
val = val.split(/[^0-9/]/).join('');
if (val.length === 2) {
val += '/';
} else {
val = val.substring(0, 6);
}
} else if (key === 'security_number') {
val = val.split(/[^0-9]/).join('');
val = val.substring(0, 4);
}
return val.trim();
};
commitTimer = setTimeout(() => {
this.cardFields[ind] = {...cardFields, ...formatFields(cardFields, cardFields.val)};
setTimeout(() => {
const currentElm = this.cardNumberInput.toArray()[ind].nativeElement;
currentElm.focus(); // will focus current input field
currentElm.selectionStart = currentElm.selectionEnd = 10000; // will move cursor to end of input field
}, 0);
}, 500);
}
...
}

主要更改:在您的变通方法中,您正在处理$event.target,它在渲染后消失,我使用了viewChild重新发送后聚焦输入并将光标移动到的末尾

在这两种情况下,请告诉我它是否有效。

最新更新