Select PrimeNG 上的行 Table With Keypress

Select Rows On PrimeNG Table With Keypress

我正在使用 PrimeNG table,并试图通过按键 select pSelectableRow 的行。

我有一个全局搜索输入,可以过滤 table 的所有结果,当用户完成搜索时,我希望他们能够单击键盘上的一个按钮并获得该行select从过滤后的选项中编辑。

目前,如果用户正在搜索并且输入框有焦点,他们可以按 tab ,但他们必须按 5 次才能下到第一行(如果有更多,则更多列)。

是否可以通过打字稿或其他方法 select 应用程序组件中的行元素,在按键时,第一行将被 selected?当然,用户可以按 enter 实际 select 该行。一旦行处于活动状态,向上和向下箭头就会起作用,但您需要先到达行。

我在我的应用程序中设置了一个热键功能,以便 f1 键触发一个事件:

this.addShortcut({ keys: 'f1' }).subscribe(() => {
  this.showMessage();
  console.log(this.table.value);
});

这显示了一条来自 PrimeNG 消息服务的消息,以确保热键正常工作,它还将 table 的值记录到控制台。我已经查看了 table 并且似乎没有任何方法可以 selecting 一行。我已经尝试设置 this.table.selection = this.table.value[1],这确实将 [1] 数组项存储为“selected 值”,但这实际上并没有 select [=] 中的任何项39=].

有更好的方法吗? 为了简化在 Whosebug 中重现此代码所需的代码,我改为包含一个 stackblitz。 这是一个stackblitz.

如果您将 [(selection)]="selectedProduct" (onFilter)="onFilter($event, dt)" 添加到您的组件中的 table 声明,那么您可以在每次用户以这种方式进行搜索时管理您的 table 选择:

onFilter(event, dt) {
    if (event.filteredValue.length > 0) {
      this.selectedProduct = event.filteredValue[0]; // set first visible row as selected
    }
  }

StackBlitz

这是你要找的吗?

编辑:

好的,希望我已经了解您的需求。我添加了三个 HostListener 来沿着过滤后的数据导航并在按下 Enter 键的同时执行一个操作:

  @HostListener('keydown.ArrowUp', ['$event']) ArrowUp($event: KeyboardEvent) {
    if (this.cpt > 0) {
      this.cpt--;
    }
    this.selectedProduct = this.visibleProducts[this.cpt];
  }

  @HostListener('keydown.ArrowDown', ['$event']) ArrowDown(
    $event: KeyboardEvent
  ) {
    if (this.cpt < this.visibleProducts.length - 1) {
      this.cpt++;
    }
    this.selectedProduct = this.visibleProducts[this.cpt];
  }

  @HostListener('keydown.Enter', ['$event']) Enter($event: KeyboardEvent) {
    alert('opening product: ' + this.selectedProduct.name);
  }

现在,onFilter 方法如下所示:

  onFilter(event, dt) {
    this.cpt = 0;
    if (event.filteredValue.length > 0) {
      this.selectedProduct = event.filteredValue[0];
      this.visibleProducts = event.filteredValue;
    }
  }