Angular-ng-zorro ZTree组件实现

令狐烨烨
2023-12-01

异步加载及拖拽实现

异步加载实现

可以如下代码(zorro官网拷贝),异步加载数据

import { Component } from '@angular/core';
import { NzFormatEmitEvent, NzTreeNodeOptions } from 'ng-zorro-antd/core';

@Component({
  selector: 'nz-demo-tree-dynamic',
  template: `
    <nz-tree [nzData]="nodes" nzAsyncData (nzClick)="nzEvent($event)" (nzExpandChange)="nzEvent($event)"> </nz-tree>
  `
})
export class NzDemoTreeDynamicComponent {
  nodes = [
    { title: 'Expand to load', key: '0' },
    { title: 'Expand to load', key: '1' },
    { title: 'Tree Node', key: '2', isLeaf: true }
  ];

  nzEvent(event: Required<NzFormatEmitEvent>): void {
    console.log(event);
    // load child async
    if (event.eventName === 'expand') {
      const node = event.node;
      if (node && node.getChildren().length === 0 && node.isExpanded) {
        this.loadNode().then(data => {
          node.addChildren(data);
        });
      }
    }
  }

  loadNode(): Promise<NzTreeNodeOptions[]> {
    return new Promise(resolve => {
      setTimeout(
        () =>
          resolve([
            { title: 'Child Node', key: `${new Date().getTime()}-0` },
            { title: 'Child Node', key: `${new Date().getTime()}-1` }
          ]),
        1000
      );
    });
  }
}

添加nzExpandChange事件,然后判断事件名是否是展开,如果展开则调用加载子节点事件。

异步拖拽实现

依然先贴官网代码(这里使用二次校验拖拽实现)

import { Component } from '@angular/core';
import { NzFormatBeforeDropEvent } from 'ng-zorro-antd/core';
import { of, Observable } from 'rxjs';
import { delay } from 'rxjs/operators';

@Component({
  selector: 'nz-demo-tree-draggable-confirm',
  template: `
    <nz-tree [nzData]="nodes" nzDraggable nzBlockNode [nzBeforeDrop]="beforeDrop"> </nz-tree>
  `
})
export class NzDemoTreeDraggableConfirmComponent {
  nodes = [
    {
      title: '0-0',
      key: '100',
      expanded: true,
      children: [
        {
          title: '0-0-0',
          key: '1001',
          children: [{ title: '0-0-0-0', key: '10010', isLeaf: true }, { title: '0-0-0-1', key: '10011', isLeaf: true }]
        },
        {
          title: '0-0-1',
          key: '1002',
          children: [{ title: '0-0-1-0', key: '10020', isLeaf: true }]
        }
      ]
    }
  ];

  beforeDrop(arg: NzFormatBeforeDropEvent): Observable<boolean> {
    // if insert node into another node, wait 1s
    if (arg.pos === 0) {
      return of(true).pipe(delay(1000));
    } else {
      return of(false);
    }
  }
}

添加可拖拽nzDraggable、节点占据一行nzBlockNode,拖拽二次校验事件nzBeforeDrop
这里说下NzFormatBeforeDropEvent的api,
属性 说明 类型 默认值
dragNode 当前拖拽节点(拖拽时存在) NzTreeNode -
node 当前操作节点(拖拽时表示目标节点) NzTreeNode -
pos 放置位置(-1:目标节点前面, 0: 目标节点内部, 1: 目标节点后面)

经过试验,拖拽会产生两个“node”
第一个则是操作的node,第二个则是拖拽后“影响”的节点,这里成为影响。由此可组合一起判断出节点放到那个位置了。
例如:node1 20,node2 10
pos为-1或者1,则代表node1和node2同一个父节点。
pos为0,则代表node1的父节点在node2。

 类似资料: