我正在使用嵌套的材料垫树..在这里,我想存储在模型/服务中扩展了哪个节点,并想获取存储的数据并显示扩展的节点。当用户刷新浏览器时,存储的数据应处于初始状态。请帮帮我。
答案 0 :(得分:0)
一旦您遍历数据。一个var扩展到它。选择节点后,将该节点数据与实际数据(通过遍历)进行匹配,并更新该数据并将其存储在服务中。
HTML
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl" class="example-tree">
<mat-tree-node *matTreeNodeDef="let node">
<li class="mat-tree-node">
<button mat-icon-button disabled></button>
{{node.title}}
</li>
</mat-tree-node>
<mat-nested-tree-node *matTreeNodeDef="let node; when: hasChild">
<li>
<div class="mat-tree-node">
<button mat-icon-button
[attr.aria-label]="'toggle ' + node.title">
<i class="fas fa-plus-circle margin-right-5" *ngIf="!node.expanded"
(click)="expandCollapseTree(node)"></i>
<i class="fas fa-minus-circle margin-right-5" *ngIf="node.expanded"
(click)="expandCollapseTree(node)"></i>
</button>
{{node.title}}</span>
</div>
<ul [class.example-tree-invisible]="!node.expanded">
<ng-container matTreeNodeOutlet></ng-container>
</ul>
</li>
</mat-nested-tree-node>
</mat-tree>
ts
getData() {
if (this.service.data.length > 0) {
this.data.result = this.service.data;
this.dataSorce.data = this.data// show data in tree format on screen
} else {
this.service.getData().subscribe(
res => {
if (res) {
this.data = res.data;
if (this.data.length > 0) {
this.addExpandedAttr(this.data); // adding expanded attr in nested JSON
this.service.data= this.data; // store result in service
this.dataSource.data = this.data; // show data in tree format on screen
}
}
});
}
}
addExpandedAttr(data) {
if (Array.isArray(data)) { // if data is an array
data.forEach((d) => {
d.expanded = false;
this.addExpandedAttr(d);
}); // call the function on each item
} else if (data instanceof Object) { // otherwise, if data is an object
data.expanded = false; // add prop to object
(data.children || []).forEach((c) => {
this.addExpandedAttr(c); // and call function on each child
});
}
}
hasChild = (_: number, node) => !!node.children && node.children.length > 0;
expandCollapseTree(node) {
node.expanded = !node.expanded;
this.saveChangesInTree(this.data, node);
this.service.data= this.data.; // save updated result in service
}
saveChangesInTree(data, node) {
// traverse throuh each node
if (Array.isArray(data)) { // if data is an array
data.forEach((d) => {
if (d.title === node.title) {
d.expanded = node.expanded;
}
this.saveChangesInTree(d, node);
}); // call the function on each item
} else if (data instanceof Object) { // otherwise, if data is an object
(data.children|| []).forEach((f) => {
if (f.title === node.title) {
f.expanded = node.expanded;
}
this.saveChangesInTree(f, node);
}); // and call function on each child
}
}