kittencup / angular2-ama-cn

angular2 随便问
691 stars 101 forks source link

ng2中如何实现树形组件 #106

Open Imporial opened 8 years ago

Imporial commented 8 years ago

小弟在 ng1 中通过 ng-include 指令对视图页进行类似递归调用可以实现树形组件,ng2中有什么相似的指令,或者通过其他方式实现么?

kittencup commented 8 years ago

image

import {Component,Input} from 'angular2/core';

interface CategoryInterface {
    name:string;
    children?:CategoryInterface[]
}

@Component({
    selector: 'tree-category',
    directives: [TreeCategory],
    template: `
        <ul>
            <li *ngFor="#category of categories">
                {{category.name}}
                <tree-category [categories]="category.children"></tree-category>
            </li>
        </ul>
    `
})
class TreeCategory {
    @Input() categories:CategoryInterface[];
}

@Component({
    selector: 'App',
    directives: [TreeCategory],
    template: `
        <h1>app</h1>
         <tree-category [categories]="categories"></tree-category>
    `
})

export class App {

    public categories:CategoryInterface[] = [];

    constructor() {
        this.categories = [
            {
                name: 'a',
                children: [
                    {
                        name: 'a-1',
                        children: [
                            {
                                name: 'a-1-1'
                            },
                            {
                                name: 'a-1-2'
                            }
                        ]
                    },
                    {
                        name: 'a-2'
                    },
                    {
                        name: 'a-3'
                    }
                ]
            },
            {
                name: 'b',
                children: [
                    {
                        name: 'b-1'
                    },
                    {
                        name: 'b-2',
                        children: [
                            {
                                name: 'b-2-1'
                            },
                            {
                                name: 'b-2-2',
                                children: [
                                    {
                                        name: 'b-2-2-1'
                                    },
                                    {
                                        name: 'a-2-2-2'
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        name: 'b-3'
                    }
                ]
            }
        ]
    }

}
hstarorg commented 7 years ago

如果递归还需要点击item,发送外部事件呢?