You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TS文件中引用CdkListbox并调用其方法

在Angular组件中引用CdkListbox并调用其方法

要在组件的.ts文件中访问CdkListbox实例并调用官方文档中的方法,按以下步骤操作:

1. 导入依赖模块与类

首先确保在你的组件所属的NgModule中导入CdkListboxModule:

import { CdkListboxModule } from '@angular/cdk/listbox';

@NgModule({
  imports: [
    // ...其他模块
    CdkListboxModule
  ]
})
export class YourModule { }

接着在组件的.ts文件中导入CdkListbox类:

import { CdkListbox } from '@angular/cdk/listbox';

2. 通过ViewChild获取CdkListbox实例

给模板中的cdkListbox元素添加一个模板引用变量(比如#listbox),然后在组件类中用@ViewChild获取实例:

修改后的模板代码:

<ul
  #listbox
  cdkListbox
  class="w-full max-h-56 h-full overflow-x-hidden overflow-y-auto"
  data-simplebar>
  <app-select-item
    appSelectItem
    *ngFor="let item of items"
    [item]="item"
    [cdkOption]="item"
    [selected]="item.id === selectedItem!.id"
    (emit-selected-item)="setSelectedItem($event)"></app-select-item>
</ul>

组件类中获取实例:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { CdkListbox } from '@angular/cdk/listbox';

@Component({
  // ...组件元数据
})
export class YourComponent implements AfterViewInit {
  @ViewChild('listbox') listbox!: CdkListbox;

  ngAfterViewInit(): void {
    // 初始化后即可调用方法,比如设置焦点
    this.listbox.focus();
  }

  // 示例:调用导航方法实现键盘导航
  navigateToNextItem(): void {
    this.listbox.navigateTo('next');
  }

  // 示例:选中指定选项
  selectSpecificItem(item: any): void {
    this.listbox.select(item);
  }
}

3. 调用CdkListbox的内置方法

你可以根据需求调用官方文档中列出的方法,比如:

  • navigateTo(direction: 'previous' | 'next' | 'first' | 'last'): 导航到指定方向的选项
  • select(value: T): 选中指定值的选项
  • focus(): 让列表框获取焦点
  • toggle(value: T): 切换选项的选中状态(多选场景)

内容的提问来源于stack exchange,提问作者rnxfod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 03:35:24