角材料树不显示填充了数组的子元素

时间:2018-12-25 05:29:45

标签: angular tree angular-material-6

我正在尝试在用户扩展节点时动态加载子级。

问题是当我填充children数组时,mat-tree没有显示子级。如果我使用简单的* ngFor显示相同的数据,则在children数组中添加了元素时,它将显示它们。

我在这里有一个有效的示例:stackblitz example 这是代码和html

ts

import {NestedTreeControl} from '@angular/cdk/tree';
import {Component} from '@angular/core';
import {MatTreeNestedDataSource} from '@angular/material/tree';


export class PropertyLevel {
   constructor(
    public code : string,
    public hasSubLevels: boolean,
    public subproperties : PropertyLevel[]
   ){}
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
    nestedTreeControl: NestedTreeControl<PropertyLevel>;
  nestedDataSource: MatTreeNestedDataSource<PropertyLevel>;

constructor() {
    this.nestedTreeControl = new NestedTreeControl<PropertyLevel>(this._getChildren);
    this.nestedDataSource = new MatTreeNestedDataSource();

 this.nestedDataSource.data = [
  new PropertyLevel( '123', false, []),
  new PropertyLevel( '345', true, [
    new PropertyLevel( '345.a', false, null),
    new PropertyLevel( '345.b', true, []),
  ]),
  new PropertyLevel( '567', false,[]),
]; 
  } 

  hasNestedChild = (_: number, nodeData: PropertyLevel) => nodeData.subproperties;

  private _getChildren = (node: PropertyLevel) => node.subproperties;

  expandToggle(node: PropertyLevel, isExpanded: boolean): void {
    if (node.subproperties && node.subproperties.length == 0) {
      if(node.code == '123') {
        node.subproperties.push(new PropertyLevel('123.a', false, null))
      } 
      else if(node.code == '567') {
        node.subproperties.push(new PropertyLevel('567.a', false, null));
        node.subproperties.push(new PropertyLevel('567.b', false, null));
        node.subproperties.push(new PropertyLevel('567.c', false, null));
      } 
    }
  }
}

html

<mat-tree [dataSource]="nestedDataSource" [treeControl]="nestedTreeControl" class="example-tree">
  <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>
    <li class="mat-tree-node">
      <button mat-icon-button disabled></button>
      {{node.code}}
    </li>
  </mat-tree-node>

  <mat-nested-tree-node *matTreeNodeDef="let node; when: hasNestedChild">
    <li>
      <div class="mat-tree-node">
        <button mat-icon-button matTreeNodeToggle
              (click)="expandToggle(node, nestedTreeControl.isExpanded(node))"
                [attr.aria-label]="'toggle ' + node.filename">
          <mat-icon class="mat-icon-rtl-mirror">
            {{nestedTreeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
          </mat-icon>
        </button>
        {{node.code}}
      </div>
      <ul [class.example-tree-invisible]="!nestedTreeControl.isExpanded(node)">
        <ng-container matTreeNodeOutlet></ng-container>
      </ul>
    </li>
  </mat-nested-tree-node>
</mat-tree>
<div>
  <ul>
    <li *ngFor="let node of nestedDataSource.data">
      {{node.code}}<br />
      <ul>
        <li *ngFor="let subnode of node.subproperties">
          {{subnode.code}}
        </li>
      </ul>
    </li>
  </ul>
</div>

1 个答案:

答案 0 :(得分:0)

这个故事的寓意是(如果我错了,请纠正我)是在Angular vs Angularjs,或者至少是Material Tree中,开发人员必须提供更改事件,而不是自动对所有内容进行更改检测,这减少了很多幕后对象的创建,使Angular更快,更精简。

因此,解决方案是不为子代使用数组,而为BehaviorSubject,并向该类添加方法addChild。

我回到带有嵌套节点的树(https://material.angular.io/components/tree/examples)示例(https://stackblitz.com/angular/ngdvblkxajq),并调整FileNode类,并添加了addChild和addChildren方法

export class FileNode {
  kids: FileNode[] = [];
  children:BehaviorSubject<FileNode[]> = new BehaviorSubject<FileNode[]>(this.kids);
  filename: string;
  type: any;
  addChild(node:FileNode):void {
    this.kids.push(node);
    this.children.next(this.kids);
  }
  addchildren(nodes:FileNode[]) {
    this.kids = this.kids.concat(this.kids, nodes);
    this.children.next(this.kids);
  }
}

然后我更改了buildFileTree中设置子项的行,改为调用addChildren。 node.children = this.buildFileTree(value, level + 1)成为node.addchildren(this.buildFileTree(value, level + 1))

我还添加了一种方法,可以通过单击按钮来调用该方法,以将一个孩子添加到图片节点以进行测试。

    addPictureFile():void {
    var picNode = this.data.find((node) => node.filename == 'Pictures');
    var newNode = new FileNode();
    newNode.filename = 'foo';
    newNode.type = 'gif';
    picNode.addChild(newNode);
  }

现在,“材料树”确实检测到我的孩子变化并进行了自我更新。 工作示例https://stackblitz.com/edit/angular-addchildtonestedtree

完整,更新的ts文件:

import {NestedTreeControl} from '@angular/cdk/tree';
import {Component, Injectable} from '@angular/core';
import {MatTreeNestedDataSource} from '@angular/material/tree';
import {BehaviorSubject} from 'rxjs';

/**
 * Json node data with nested structure. Each node has a filename and a value or a list of children
 */
export class FileNode {
  kids: FileNode[] = [];
  children:BehaviorSubject<FileNode[]> = new BehaviorSubject<FileNode[]>(this.kids);
  filename: string;
  type: any;
  addChild(node:FileNode):void {
    this.kids.push(node);
    this.children.next(this.kids);
  }
  addchildren(nodes:FileNode[]) {
    this.kids = this.kids.concat(this.kids, nodes);
    this.children.next(this.kids);
  }
}

/**
 * The Json tree data in string. The data could be parsed into Json object
 */
const TREE_DATA = JSON.stringify({
  Applications: {
    Calendar: 'app',
    Chrome: 'app',
    Webstorm: 'app'
  },
  Documents: {
    angular: {
      src: {
        compiler: 'ts',
        core: 'ts'
      }
    },
    material2: {
      src: {
        button: 'ts',
        checkbox: 'ts',
        input: 'ts'
      }
    }
  },
  Downloads: {
    October: 'pdf',
    November: 'pdf',
    Tutorial: 'html'
  },
  Pictures: {
    'Photo Booth Library': {
      Contents: 'dir',
      Pictures: 'dir'
    },
    Sun: 'png',
    Woods: 'jpg'
  }
});

/**
 * File database, it can build a tree structured Json object from string.
 * Each node in Json object represents a file or a directory. For a file, it has filename and type.
 * For a directory, it has filename and children (a list of files or directories).
 * The input will be a json object string, and the output is a list of `FileNode` with nested
 * structure.
 */
@Injectable()
export class FileDatabase {
  dataChange = new BehaviorSubject<FileNode[]>([]);

  get data(): FileNode[] { return this.dataChange.value; }

  constructor() {
    this.initialize();
  }

  initialize() {
    // Parse the string to json object.
    const dataObject = JSON.parse(TREE_DATA);

    // Build the tree nodes from Json object. The result is a list of `FileNode` with nested
    //     file node as children.
    const data = this.buildFileTree(dataObject, 0);

    // Notify the change.
    this.dataChange.next(data);
  }

  /**
   * Build the file structure tree. The `value` is the Json object, or a sub-tree of a Json object.
   * The return value is the list of `FileNode`.
   */
  buildFileTree(obj: {[key: string]: any}, level: number): FileNode[] {
    return Object.keys(obj).reduce<FileNode[]>((accumulator, key) => {
      const value = obj[key];
      const node = new FileNode();
      node.filename = key;

      if (value != null) {
        if (typeof value === 'object') {
          node.addchildren(this.buildFileTree(value, level + 1));
        } else {
          node.type = value;
        }
      }

      return accumulator.concat(node);
    }, []);
  }
    addPictureFile():void {
    var picNode = this.data.find((node) => node.filename == 'Pictures');
    var newNode = new FileNode();
    newNode.filename = 'foo';
    newNode.type = 'gif';
    picNode.addChild(newNode);
  }
}

/**
 * @title Tree with nested nodes
 */
@Component({
  selector: 'tree-nested-overview-example',
  templateUrl: 'tree-nested-overview-example.html',
  styleUrls: ['tree-nested-overview-example.css'],
  providers: [FileDatabase]
})
export class TreeNestedOverviewExample {
  nestedTreeControl: NestedTreeControl<FileNode>;
  nestedDataSource: MatTreeNestedDataSource<FileNode>;

  constructor(private database: FileDatabase) {
    this.nestedTreeControl = new NestedTreeControl<FileNode>(this._getChildren);
    this.nestedDataSource = new MatTreeNestedDataSource();

    database.dataChange.subscribe(data => {
    this.nestedDataSource.data = data;
    }
    );
  }

  hasNestedChild = (_: number, nodeData: FileNode) => !nodeData.type;

  private _getChildren = (node: FileNode) => node.children;
}