我目前正在使用复选框构建动态树组件。想法是在选择节点时扩展其所有后代。我正在尝试使用expandAllDescendants()
方法,但是由于某种原因,它仅扩展了所选节点的第一级子级。我正在使用Map<TreeNode, TreeNode[]>
来保存树的层次结构。它基于此Angular Material tree with dynamic data example
我什至尝试使用@Viewchild()
,然后在expand(selectedNode)
中调用ngAfterViewInit()
方法,但是此方法给我的结果与上面相同。
Component.ts文件
selectAndExpand(treeNode: FlatTreeNode): void {
let stack = new Stack();
stack.pushStack(treeNode.node);
treeNode.node.nodeSelected = !treeNode.node.nodeSelected;
this.treeControl.expandDescendants(treeNode);
while (stack.stack.length !== 0) {
let removedNode = stack.popStack();
removedNode.nodeSelected = treeNode.node.nodeSelected;
if (this.dataSource.database.treeMap.has(removedNode)) {
for (let child of this.dataSource.database.treeMap.get(removedNode)) {
stack.pushStack(child);
}
}
}
HTML文件
<mat-tree #tree [dataSource]="dataSource" [treeControl]="treeControl">
<mat-tree-node *matTreeNodeDef="let treeNode" matTreeNodePadding>
<button mat-icon-button disabled></button>
<mat-checkbox
class="tree-node-active"
[checked]="treeNode.node.nodeSelected"
(change)="selectAndExpand(treeNode)"
color="warn"
>
{{ treeNode.node.nodeName }}
</mat-checkbox>
</mat-tree-node>
<mat-tree-node
*matTreeNodeDef="let treeNode; when: hasChild"
matTreeNodePadding
>
<button
class="expand-collapse-button"
mat-icon-button
[attr.aria-label]="'toggle ' + treeNode.node.nodeName"
matTreeNodeToggle
>
<mat-icon class="mat-icon-rtl-mirror">
{{
treeControl.isExpanded(treeNode)
? "expand_more"
: "chevron_right"
}}
</mat-icon>
</button>
<mat-checkbox
class="tree-node-active"
[checked]="treeNode.node.nodeSelected"
(change)="selectAndExpand(treeNode)"
color="warn"
>
{{ treeNode.node.nodeName }}
</mat-checkbox>
<mat-progress-bar
*ngIf="treeNode.isLoading"
mode="indeterminate"
class="example-tree-progress-bar"
></mat-progress-bar>
</mat-tree-node>
</mat-tree>```