为什么`setAllSelected`不触发`listbox.valueChange`事件,我们如何让它发出?

问题描述 投票:0回答:1

为什么

setAllSelected
不导致
listbox.valueChange
发射?我们怎样才能确保它发射?

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

/** @title Listbox with aria-activedescendant. */
@Component({
  selector: 'cdk-listbox-activedescendant-example',
  exportAs: 'cdkListboxActivedescendantExample',
  templateUrl: 'cdk-listbox-activedescendant-example.html',
  styleUrl: 'cdk-listbox-activedescendant-example.css',
  standalone: true,
  imports: [CdkListbox, CdkOption],
})
export class CdkListboxActivedescendantExample {
  @ViewChild('listbox', { static: true, read: CdkListbox })
  private listbox!: CdkListbox<any>;
  ...
  ngOnInit() {
    this.listbox.valueChange.subscribe((result) => {
      console.log({ result });
    });

    this.listbox.setAllSelected(true);

    console.log({ listboxInstance: this.listbox });
  }
}

stackblitz 示例

javascript angular angular-material angular-material2
1个回答
0
投票

cdkOption的钩子下:

  this.selectionModel.select(...this.options.map(option => option.value));

所以当你在 ngOnit生命周期-hooks 中声明 this.listBox.setAllselected(true) 时, options 的值仍然是 undefined 并导致 无法读取 undefined 的属性

当您将其移至 ngAfterViewInit 时,在 Angular 初始化组件的视图等之后,该值将被正确定义。

  ngAfterViewInit() {
    this.listbox.setAllSelected(true);
  }

在调用 setAllSelected 方法之前,您需要等待视图初始化。

© www.soinside.com 2019 - 2024. All rights reserved.