angular: tree-view

需要一个tree来显示有父子关系的列表:

tree-view.html

<ul>
    <li *ngFor = "let node of nodes">
        <span class="fa" [ngClass]="{'fa-plus':!node.expanded,'fa-minus':node.expanded}"
         (click)="node.toggle()"></span>
         <a href="#">
            <span (click)="doSomething(node)" [ngClass]="{'active':staticCurrentNode===node}">{{node.name}}</span>
         </a>        
        <div *ngIf="node.expanded">
            <ul>
                <li *ngFor="let leaf of node.childLeaves">                    
                    <span class="fa fa-minus"></span>
                    <a href="#">
                        <span (click)="doSomething(leaf)" [ngClass]="{'active':staticCurrentNode===leaf}">{{leaf.name}}</span>
                    </a>                    
                </li>
            </ul>
            <tree-view #innerTreeView [nodes]="node.childNodes" (doSomethingEvent)="popEventHandler($event)"></tree-view>
        </div>
    </li>
</ul>

tree-view.ts

import { Component, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { TreeNode } from './tree-node';

@Component({
    selector: 'tree-view',
    templateUrl: './tree-view.html',
    styleUrls: ['./tree-view.css']
})

export class TreeViewComponent<T> implements OnInit {

    static currentNode: any;

    @Input() nodes: TreeNode<T>[];
    @Output() doSomethingEvent = new EventEmitter<TreeNode<T>>();

    get staticCurrentNode() {
        return TreeViewComponent.currentNode;
    }

    doSomething(node: TreeNode<T>): boolean {
        console.log('doSomething:', node.name);
        TreeViewComponent.currentNode = node;
        this.doSomethingEvent.emit(node);
        return false;
    }

    ngOnInit(): void {
        // console.log(this.nodes);
        // console.log(this.nodes.length);
    }

    ngOnChanges(changes: SimpleChanges) {
        // if(changes['nodes']){
        //     console.log(this.nodes);
        // }
    }

    popEventHandler(node: TreeNode<T>): boolean {
        console.log('popEventHandler:', node.name);
        this.doSomethingEvent.emit(node);
        return false;
    }
}

tree-view.css

ul{
    list-style:none;
}

span{
    color:#00a65a;
}

span.fa{
    color:#008d4c;
}

span.active{
    background-color:#00a65a;
    color:#fff;
}

tree-node.ts

export class TreeNode<T>{
    name:string;
    node:T;
    parent:TreeNode<T>;
    childLeaves:TreeNode<T>[]; // 叶子节点
    childNodes:TreeNode<T>[]; // 子节点中依然包含子节点

    expanded:boolean = false;

    constructor(){
        this.childLeaves = [];
        this.childNodes = [];
    }

    toggle(){
        this.expanded = !this.expanded;
    }
}

 

参考:

http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0

posted @ 2017-09-29 16:06  Jane&Coding  阅读(194)  评论(0)    收藏  举报