如何默认在下拉菜单中打开 tree-select

How to open tree-select in a dropdown menu by default

我正在尝试找到一种方法如何使 nz-tree-select 在下拉菜单项单击时默认打开。

Link to stackblitz

我正在尝试使用来自 nz-dropdown(nzVisibleChange) 事件和 [(nzOpen)] 来自 nz-tree-select 的状态。但现在没有运气。 我也可以访问 NzTreeSelectComponent,但我不确定如何使用它。

<button nz-button nz-dropdown [nzDropdownMenu]="menu"
      (nzVisibleChange)="dropDownVisibleChange($event)"
      nzPlacement="bottomLeft"
      nzTrigger="click">Button
</button>

<nz-dropdown-menu #menu="nzDropdownMenu">
  <nz-tree-select #tree [(nzOpen)]="isOpen" class="tree-select" nzNoAnimation nzShowExpand [nzMaxTagCount]="2"
    [nzNodes]="nodes" [nzHideUnMatched]="true" nzVirtualHeight="498px" [nzShowSearch]="true" nzCheckable
    nzPlaceHolder="Please select">
  </nz-tree-select>
</nz-dropdown-menu>
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit, AfterContentInit {
  isOpen: boolean;
  @ViewChild(NzTreeSelectComponent, { static: true })
  tree: NzTreeSelectComponent;
  nodes = [
    {
      title: "parent 1",
      key: "100",
      children: [
        {
          title: "parent 1-0",
          key: "1001",
          children: [
            { title: "leaf 1-0-0", key: "10010", isLeaf: true },
            { title: "leaf 1-0-1", key: "10011", isLeaf: true }
          ]
        },
        {
          title: "parent 1-1",
          key: "1002",
          children: [{ title: "leaf 1-1-0", key: "10020", isLeaf: true }]
        }
      ]
    }
  ];

  dropDownVisibleChange(open: boolean): void {
    console.log("VisibleChange", open);
    this.isOpen = open;
  }

  ngAfterViewInit(): void {
    console.log(this.tree);
  }

  ngAfterContentInit(): void {
    console.log(this.tree);
  }
}

如果您查看 nz-tree-select 的 source code,这里有两个有用的 public 函数可以帮助您解决问题,openDropdowncloseDropDownnzOpen 布尔标志在这里没有帮助,因为它不会触发下拉菜单。

在您的组件中,您可以进行以下更改:

dropDownVisibleChange(open: boolean): void {
    if (open) {
      setTimeout(() => this.tree.openDropdown());
    } else {
      this.tree.closeDropDown();
    }
  }

结果是,当您切换下拉列表(其中包含树 select)时,您也会切换树 select 的下拉列表。 setTimeout 的原因是当该事件被触发打开时,下拉菜单还不可见。

这是一个stackblitz demo