我在p-tree(primeng)上有这些数据,我想知道是否可以在初始加载中选择所有选中的值。我试图在selectFiles'上放置一个新数组,当前数据,同一级别的父级和子级,在数组上,只与父节点一起工作,但子节点是不工作。
数据:
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
答案 0 :(得分:0)
您最有可能必须编写一个递归函数来逐步执行每个项目的子项,以将项目作为数据变量selectedFiles
添加到filesTree
变量,尽管数组只是一系列顶级父母。
答案 1 :(得分:0)
首先,将所有节点添加到数组的方法
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
}
答案 2 :(得分:-1)
<p-tree [value]="_CategoriesTree" selectionMode="checkbox" [(selection)]="_selectedNode"></p-tree>
selectAll() {
this._selectedNode = [];
this.selectAllRecursive(this._CategoriesTree);
}
private selectAllRecursive(tree: TreeNode[]) {
for (const node of tree) {
this._selectedNode.push(node);
if (node.children) {
this.selectAllRecursive(node.children);
}
}
}