简体   繁体   English

angular 9 和 angular 材料中树中的预选项目

[英]pre-selected items in tree in angular 9 and angular material

i create tree in angular material and angular 9.我在 angular 材料和 angular 9 中创建树。

Demo 演示

but i have a problem.但我有一个问题。 i have items in my items my be have child or not.我的物品中有物品,我有没有孩子。

when I create a tree every items not having any child get pre-selected, but I dont need do this.当我创建一棵树时,每个没有孩子的项目都会被预先选择,但我不需要这样做。

    rolesToTree(roles): void {
    console.log(JSON.stringify(roles))
    const selections: ItemFlatNode[] = [];
    const controllers = [];
    roles.forEach(element => {
        const attrs = [];
        element['children'].forEach(attr => {
            const secAttrs = [];
                attr['children'].forEach(sec => {
                    const secAction = { name: sec['title'], actionId: sec['id'] };
                    secAttrs.push(secAction);
                    if (sec['selected'] === true) {
                        const a = new ItemFlatNode(false, sec['id'], sec['title'], 3);
                        selections.push(a);
                    }
                });
            if (attr['selected'] === true) {
                const a = new ItemFlatNode(false, attr['id'], attr['title'], 2);
                selections.push(a);
            }
            const actionss = { name: attr['title'], actionId: attr['id'], children: secAttrs };
            attrs.push(actionss);
        });
        const controller = { name: element['title'], actionId: element['id'], children: attrs };
        controllers.push(controller);
    });
    // this.checklistSelection = new SelectionModel<ItemFlatNode>(true, selections);
    this.defualtSelected = selections;

    const data = [{ name: 'All', actionId: 'sds', children: controllers }];
    this.database.dataChange.next(this.database.builTree(data, 0));
}

whats the problem?有什么问题? how can i solve this problem????我怎么解决这个问题????

Method descendantsAllSelected verifies for every child node is selected, which will return true if there is no descendant element.方法 descendantsAllSelected 验证每个子节点是否被选中,如果没有后代元素,它将返回 true。

To fix that, need to check for descendants length and if that is 0, return node node selected value.要解决此问题,需要检查后代长度,如果为 0,则返回节点节点选定值。

Update descendantsAllSelected method as below:更新 descendantsAllSelected 方法如下:

    descendantsAllSelected(node: ItemFlatNode): boolean {
       const descendants = this.treeControl.getDescendants(node);
       return (this.checklistSelection.isSelected(node) && descendants.length==0) || (descendants.length>0 && descendants.every(child => this.checklistSelection.isSelected(child)));
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM