Angular2句柄单击递归子级的父级

时间:2016-03-15 19:27:26

标签: recursion typescript angular

我创建了一个动态递归(树)节点组件,它由服务器的json谐振器构建。树组件中处理的请求和响应。我尝试在我的应用程序中处理所有子点击事件。后来我喜欢使用子路由,它允许使用点击的节点数据加载内容页面。

我刚刚开始使用angular2,所以如果您认为这是一个完全错误的概念,请告诉我们。)

tree.ts:

@Component({
    selector: 'tree',
    template: '
        <div (click)="onClick($event)" class="tree">
            <node *ngIf="data" [key]="key" [data]="data"></node>
        </div>
    ',
    ...
})
export class TreeComponent {
    key: string;
    data: any;
    error: any;

    ngOnInit() {
        this.key = 'tree';
        let url = 'http://localhost:53494/api/tree';

        this.http.get(url)
        .map(res => res.json())
        .subscribe(
            value => this.data = value,
            error => this.error = error);

    }
    ...
    onClick($event: any) {//This will recieves all click of all node!
        $event.preventDefault();

        //1. How to get the clicked node's key and data here?
        //2. How to (sub/child)route to './tree/' + [node].key?
    }
    ...
}

node.ts:

@Component({
    selector: 'node',
    directives: [NodeComponent], //<<< use self!
    template: '
        <a href="" class="node collapsed" 
           [attr.data-toggle]="data.node ? 'collapse' : null" 
           [attr.data-target]="'#' + nodePath" 
           aria-expanded="false" >               
           <span class="ident-{{level}}">
              {{data.name || key}}
           </span>
        </a>
        <div [id]="nodePath" class="tree collapse">
           <node *ngFor="#nodeKey of nodeKeys" 
              [path]="nodePath" 
              [key]="nodeKey" 
              [level]="level+1" 
              [data]="data.node[nodeKey]">
           </node>
        </div>
    '
    ...
})
export class NodeComponent {
    @Input() key: string;
    @Input() data: any;
    @Input() level: number = 0;
    @Input() path: string = 'node';

    private nodePath: string;
    private nodeKeys: Array<string>;

    ngOnInit() {
        this.nodePath = this.path + '-' + this.key;
        if (this.data.node) {
            this.nodeKeys = Object.keys(this.data.node);
        }
    }

}

0 个答案:

没有答案