指令导致输入失去焦点

时间:2019-09-13 18:55:43

标签: angular

我创建了此指令:

@Directive({
  selector: 'input[numbersOnly]'
})
export class NumbersOnlyDirective {

  constructor(private ref: ElementRef, private control: NgControl) { }

  @HostListener('input', ['$event']) onInputChange(event: Event) {
    const initalValue = this.ref.nativeElement.value;
    this.ref.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
    this.control.control.patchValue(this.ref.nativeElement.value);
    if (initalValue !== this.ref.nativeElement.value) {
      event.stopPropagation();
    }
  }
}

并在这里使用它:

<ng-container matColumnDef="quantity">
  <th
    class="header-title-2"
    mat-header-cell
    *matHeaderCellDef
    mat-sort-header="quantity"
  >
    Quantity
    <div class="sort-indicator" [ngClass]="{ desc: sortDirection }">
      {{ sortIndicator('quantity') }}
    </div>
  </th>
  <td mat-cell *matCellDef="let item">
    <input
      [ngClass]="{ 'input-error': item.quantity > 99 }"
      matInput
      numbersOnly
      class="input-background"
      [(ngModel)]="item.quantity"
      (ngModelChange)="updateQuantity(item)"
      maxlength="99"
    />
    <div class="quantity-error" *ngIf="item.quantity > 99">
      Max quantity is 99
    </div>
  </td>
</ng-container>

但是,每次我在输入中输入字符时,它都会失去焦点,从而导致用户不得不重新聚焦它才能输入字符。

我尝试获取nativeElement的输入的句柄并调用focus方法,但是即使使用超时,似乎也没有任何作用。

1 个答案:

答案 0 :(得分:0)

实际上是导致问题的ngModelChange。我将其更改为使用模糊方法,并解决了该问题。

要添加更多内容,我正在使用异步管道绑定数据,并且每次按键时都会更新我的状态模型,我相信这会触发更新,从而将我的数据重新加载到页面上,导致输入失去焦点。基本上,它是重新渲染页面的某些部分,如预期的那样进行更改,从而又将焦点移开了。

希望这对某人有帮助。