【发布时间】:2018-12-25 05:29:44
【问题描述】:
我试图在用户展开节点时动态加载子节点。
问题是当我填充孩子数组时,mat-tree 没有显示孩子。如果我使用简单的 *ngFor 显示相同的数据,当子数组添加了元素时,它会显示它们。
我在这里有一个工作示例: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>
【问题讨论】:
-
我觉得比你想象的要复杂,查看文档中的动态数据部分:material.angular.io/components/tree/examples。我认为数据更改不会触发 UI 更改,因此您需要根据示例实现动态数据源。
标签: angular tree angular-material-6