递归地使用组件本身来创建一棵树 [英] Use component in itself recursively to create a tree
问题描述
你知道可以单独使用组件吗?如果是,在哪里可以阅读?
我有下一个情况:有 mainItems 列表,每个 Main Item 都有 subItem(看起来与 mainItem 相同),每个 subItem 可以有它自己的 subItem 等.所以最好使用嵌套,但如何使用?
更新
forwardRef()
不再需要,因为 directives
已移至 NgModule.declarations
,因此不需要递归组件自己注册为 directives
了.
原创
支持.您只需要将组件添加到 directives: []
的 @Component()
装饰器中.因为装饰器在类之前,并且类在声明之前不能被引用 forwardRef()
是必要的.
import {Component, forwardRef, Input} from '@angular/core'@成分({选择器:'树节点',模板:`<div>{{node.name}}</div><ul><li *ngFor="let node of node.children"><树节点[节点]=节点"></树节点>`})导出类 TreeNode {@Input() 节点;}
@Component({选择器:'我的应用',模板:`<div><h2>你好{{name}}</h2><树节点[节点]=节点"></树节点>
`,指令:[TreeNode]})出口类应用{构造函数(){this.name = 'Angular2(发布候选!)'}节点 = {名称:'根',孩子:[{名称:'a',孩子:[]},{名称:'b',孩子:[]},{名称:'c',儿童:[{名称:'d',孩子:[]},{名称:'e',孩子:[]},{名称:'f',孩子:[]},]},]};}
Angular 2.0.0-beta.x Plunker 示例
Do you know is it possible to use component in itself? If yes,where to read about it?
I have next situation: have list of mainItems, every Main Item has subItem (the same look like mainItem), every subItem can have it's own subItem etc. So it better to use nesting,but how?
update
forwardRef()
isn't required anymore because directives
was moved to NgModule.declarations
and therefore recursive components don't need to be registered on themselves as directives
anymore.
original
That supported. You just need to add the component to directives: []
in its @Component()
decorator. Because the decorator comes before the class and classes can't be referenced before they are declared forwardRef()
is necessary.
import {Component, forwardRef, Input} from '@angular/core'
@Component({
selector: 'tree-node',
template: `
<div>{{node.name}}</div>
<ul>
<li *ngFor="let node of node.children">
<tree-node [node]="node"></tree-node>
</li>
</ul>
`
})
export class TreeNode {
@Input() node;
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<tree-node [node]="node"></tree-node>
</div>
`,
directives: [TreeNode]
})
export class App {
constructor() {
this.name = 'Angular2 (Release Candidate!)'
}
node = {name: 'root', children: [
{name: 'a', children: []},
{name: 'b', children: []},
{name: 'c', children: [
{name: 'd', children: []},
{name: 'e', children: []},
{name: 'f', children: []},
]},
]};
}
Angular 2.0.0-beta.x Plunker example
See also Inject parent component of the same type as child component
这篇关于递归地使用组件本身来创建一棵树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!