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

mr coder :

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 ????

Gourav Garg :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=404954&siteId=1