nunoarruda nunoarruda - 2 months ago 130
TypeScript Question

How to expand/collapse a recursive tree view in Angular 2?

I'm trying to reproduce the expand/collapse functionality from this AngularJS 1 demo into my Angular 2 app (I'm using a recursive view) but my attempts always result in expanding more than 1 node.

How could I achieve a proper expand/collapse functionality in Angular 2?

Here's my current code:

import {Component, Input} from '@angular/core';

@Component ({
selector: 'tree-view',
template: `
<ul>
<li *ngFor="let node of treeData">
<span *ngIf="node.children?.length" (click)="toggleChildren()">[+]</span>
{{node.name}}
<tree-view [treeData]="node.children"></tree-view>
</li>
</ul>
`
})
export class TreeView {
@Input() treeData: any[];

toggleChildren() {
// to do
}
}


Here's a Plunker with everything: http://plnkr.co/edit/KmLDb1ba3WYp3X6snnmg?p=preview

Answer

Add property to the nodes to check whether they're visible or not. If they're you show them, if not you hide them.

This is a simple of example of how you can implement it. You may want to improve it by changing the icon [+] for a [-] when the node are visible.

import {Component, Input} from '@angular/core';

@Component ({
    selector: 'tree-view',
    template: `
    <ul>
        <li *ngFor="let node of treeData">
            <span *ngIf="node.children?.length" (click)="toggleChildren(node)">[+]</span>
            {{node.name}}
            <tree-view [treeData]="node.children" *ngIf="node.visible"></tree-view>
        </li>
    </ul>
    `
})
export class TreeView {
    @Input() treeData: any[];


    toggleChildren(node: any) {
      // to do
      node.visible = !node.visible;

    }
}
Comments