如何选择素数角p-树上的所有节点?
问题描述:
我在p-tree(primeng)上有这个数据,我想知道是否有可能把所有在初始加载中选择的值。我试图在'selectedFiles'上放置一个新数组,并且当前数据(父级和子级在数组中)仅在父节点上工作,但是子节点不工作。如何选择素数角p-树上的所有节点?
数据:
this.filesTree = [
{
"label": "Documents",
"data": "Documents Folder",
"expandedIcon": "fa-folder-open",
"collapsedIcon": "fa-folder",
"children": [{
"label": "Work",
"data": "Work Folder",
"expandedIcon": "fa-folder-open",
"collapsedIcon": "fa-folder",
"children": [{"label": "Expenses.doc", "icon": "fa-file-word-o", "data": "Expenses Document"}, {"label": "Resume.doc", "icon": "fa-file-word-o", "data": "Resume Document"}]
},
{
"label": "Home",
"data": "Home Folder",
"expandedIcon": "fa-folder-open",
"collapsedIcon": "fa-folder",
"children": [{"label": "Invoices.txt", "icon": "fa-file-word-o", "data": "Invoices for this month"}]
}]
}
];
角码:
export class TreeDemo implements OnInit {
msgs: Message[];
@ViewChild('expandingTree')
expandingTree: Tree;
selectedFile: TreeNode;
constructor(private nodeService: NodeService) { }
ngOnInit() {
this.nodeService.getFiles().then(files => this.filesTree = files);
}
selectAll(){
// with the parent nodes is working
this.selectedFiles = this.filesTree.map(
files => {
... files
})
//this is an example of how I want to store but is not working
this.filesTree
.map(files => {
this.selectedFiles = files.children
.map(file => {
return {
... file,
parent: files
};
});
});
}
模板:
<h3>Multiple Selection with Checkbox</h3>
<p-tree
[value]="filesTree"
selectionMode="checkbox"
[(selection)]="selectedFiles">
</p-tree>
<div>Selected Nodes:
<span *ngFor="let file of selectedFiles2">{file.label} </span>
</div
答
你最有可能将不得不写一个递归函数来逐步完成每个项目的子项将项目添加到selectedFiles
变量作为数据变量filesTree
虽然是一个数组,但它只是*父母的数组。
答
首先,用于将所有节点的数组方法
flattenTree(node : TreeNode)
{
this.arr.push(node);
if (node.children)
{
node.children.forEach(childNode => {
this.flattenTree(childNode);
});
}
}
然后设置selectedItems =所有节点的数组
test(node)
{
this.filesTree11.forEach(node => {
this.flattenTree(node);
});
this.selectedItems = this.arr; // select all nodes
}