Home > Mobile >  Nz TreeSelect. How to display parent node name in children?
Nz TreeSelect. How to display parent node name in children?

Time:09-06

I have tree select with options. When i click on Name, it displays Name, but I want it to be Item > Name, because this is children node. What should I do ? I found [nzDisplayWith], but it doesn't help.

    const options = [{
    {
            title: 'Item',
            key: 'Item',
            children: [
                {
                    title: 'Name',
                    key: 'Item-Name',
                    isLeaf: true,
                }
             ]
    },
}]

  <nz-tree-select
            style="width: 100%"
            [nzNodes]="options"
            [nzDefaultExpandAll]="true"
            aria-autocomplete="none"
            nzVirtualHeight="240px"
            formControlName="field"
        ></nz-tree-select>

CodePudding user response:

I am using a recursive function to generate the title based on the parent, I have used nzTreeTemplate to achieve this.

html

<nz-tree-select
  #tree
  
  nzNoAnimation
  nzShowExpand
  [nzMaxTagCount]="2"
  [nzNodes]="nodes"
  [nzHideUnMatched]="true"
  nzVirtualHeight="498px"
  [nzShowSearch]="true"
  nzCheckable
  nzPlaceHolder="Please select"
>
  <ng-template #nzTreeTemplate let-node let-origin="origin">
    {{ recursive(node) }}
  </ng-template>
</nz-tree-select>

ts

import {
  AfterContentInit,
  AfterViewInit,
  Component,
  ViewChild,
} from '@angular/core';
import { NzTreeSelectComponent } from 'ng-zorro-antd/tree-select';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit, AfterContentInit {
  @ViewChild(NzTreeSelectComponent, { static: true })
  tree: NzTreeSelectComponent;
  nodes = [
    {
      title: 'Item',
      key: 'Item',
      children: [
        {
          title: 'Name',
          key: 'Item-Name',
          isLeaf: true,
        },
      ],
    },
  ];

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

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

  test(node) {
    console.log(node);
  }

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

  recursive(node, output = '') {
    if (node.isLeaf && node.parentNode) {
      return this.recursive(node.parentNode, output)   ` > ${node.title}`;
    } else {
      return node.title;
    }
  }
}

forked stackblitz

  • Related