【问题标题】:How to prevent tab event in Angular?如何防止 Angular 中的选项卡事件?
【发布时间】:2021-02-12 00:09:20
【问题描述】:

我想使用 tab 键来执行一些逻辑,但实际上并没有改变焦点。根据this answer's comments,我可以在我的标记中使用 false 或在方法中使用 preventDefault() 。我两个都这样。

onKey(event: KeyboardEvent) { 
  event.preventDefault();
  if(event.key = "Tab") { this.update.emit(this.config); }
}

<input #input
   title="{{config|json}}"
   value="{{config.value}}"
   (keyup)="onKey($event)"
   (keydown.Tab)="onKey($event);false;">

不过,当我按 Tab 键时,它会额外跳转。当我尝试相同的逻辑但基于其他键(例如“a”或“enter”)时,行为符合预期,因此我得出结论认为逻辑是正确的。出于某种原因,by tab 是不守规矩的,并且会传播事件,就好像我想 tab 两次一样。

我是否错误地处理了 Tab 键?除了我已经拥有的东西之外,不知道该用谷歌搜索什么。

【问题讨论】:

  • 这并不能真正回答您的问题,但我会警惕更改选项卡功能,因为它可能会使一些辅助功能变得异常,并导致残障人士出现意外行为。
  • @Pytth 同意。这种特殊情况是为数量有限且偏僻的用户提供的应用程序,他们认为 Excel 是有史以来最好的工具,因此他们需要能够跳到下一个单元格。 :)
  • 我没有看到你描述的行为。我已经删除了所有未定义的项目:stackblitz.com/edit/angular-11zsgl?embed=1&file=src/app/…
  • @jcuypers 我确认。不过还是有问题。当我添加第二个输入框并尝试以编程方式关注它时,我可以设置它的值,但焦点停留在初始输入框。请查看the sample
  • @KonradViltersten:它可以工作:stackblitz.com/edit/angular-gbuwma?embed=1&file=src/app/…。你使用了setFocus() 而不是focus()

标签: html angular events


【解决方案1】:

从堆栈闪电战中提取:https://stackblitz.com/edit/angular-gbuwma?embed=1&file=src/app/app.component.ts

ts

import { Component, ViewChild, ElementRef,ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private changeDetector: ChangeDetectorRef) { }


  @ViewChild("input2") input2: ElementRef;

  onKey(event: KeyboardEvent) {
    event.preventDefault();
    if (event.key === "Tab") {
        console.log('ole... tab');
        this.input2.nativeElement.value = "aha";
        this.changeDetector.detectChanges();
        this.input2.nativeElement.focus();
    }

  }

}

html

<input #input
   title=""
   value=""
   (keydown.Tab)="onKey($event);false;">
 - - - 
   <input #input2
   title=""
   value=""
   (keydown.Tab)="onKey($event);false;">

【讨论】:

    【解决方案2】:

    尝试使用此代码:

    import { HostListener } from '@angular/core';
    
    @HostListener('document:keydown.tab', ['$event'])
    onKeydownHandler(event: KeyboardEvent) {
        event.preventDefault();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-21
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      • 2023-03-29
      • 2020-08-11
      • 2020-05-16
      • 1970-01-01
      相关资源
      最近更新 更多