递归使用组件本身来创建树 [英] Use component in itself recursively to create a tree
问题描述
您知道本身可以使用组件吗?如果是,请在哪里阅读?
Do you know is it possible to use component in itself? If yes,where to read about it?
我有下一种情况: 有mainItem列表,每个Main Item都有subItem(外观与mainItem相同),每个subItem都可以有自己的subItem等. 因此最好使用嵌套,但是如何使用呢?
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?
推荐答案
更新
forwardRef()
,因为directives
已被移至NgModule.declarations
,因此递归组件不再需要在其自身上注册为directives
.
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.
原始
表示支持.您只需要在@Component()
装饰器中将组件添加到directives: []
.因为装饰器位于类之前,并且在声明forwardRef()
是必需的之前不能引用这些类.
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示例
另请参见注入父组件与子组件类型相同
这篇关于递归使用组件本身来创建树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!