简体   繁体   中英

pre-selected items in tree in angular 9 and angular material

i create tree in angular material and 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.

To fix that, need to check for descendants length and if that is 0, return node node selected value.

Update descendantsAllSelected method as below:

    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)));
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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