使用递归数组加载递归组件 [英] Recursive component loading with recursive array
问题描述
我正在尝试使用递归数组递归加载Angular 2组件(plunk: http: //plnkr.co/edit/3npsad?p=preview )。
I'm trying to load an Angular 2 component recursively with a recursive array (plunk: http://plnkr.co/edit/3npsad?p=preview).
给定这个递归数组:
[
{
"id": 1,
"text": "abc"
},
{
"id": 2,
"text": "def",
items: [
{
"id": 21,
"text": "def-1",
items: [
{
"id": 211,
"text": "def-1-1"
},
{
"id": 212,
"text": "def-1-2"
}
]
},
{
"id": 22,
"text": "def-2"
}
]
}
]
我需要以下输出:
<my-item>
<div id="1" text="abc"></div>
</my-item>
<my-item>
<div id="2" text="def"></div>
<my-item>
<div id="21" text="def-1"></div>
<my-item>
<div id="211" text="def-1-1"></div>
</my-item>
<my-item>
<div id="212" text="def-1-2"></div>
</my-item>
</my-item>
<my-item>
<div id="22" text="def-2"></div>
</my-item>
</my-item>
我只能在我的plunk中显示第一级输入。如何使我的组件递归迭代以呈现所需的输出?输入数组可以包含任意数量的元素和嵌套。
I could only render the first level of input as show in my plunk. How can I make my component iterate recursively to render the desired output? The input array can contain any number of elements and nesting.
谢谢!
推荐答案
更新
引入 @NgModule
并迁移不应再需要指令
到 @NgModule
forwardRef
。
With the introduction of @NgModule
and the migration of directives
to @NgModule
forwardRef
shouldn't be necessary anymore.
原始
<my-item *ngFor="let itm of items" [id]="itm.id" [text]="itm.text" [items]="itm.items" >
</my-item>
@Component({
selector: 'my-item',
styles: ['div {padding-left: 32px;}']
providers: [],
template: `<div>{{id}} - {{text}}
<my-item *ngFor="let itm of items" [id]="itm.id" [text]="itm.text" [items]="itm.items" >
</my-item>
</div>
`,
directives: [forwardRef(()=> ItemComponent)]
})
export class ItemComponent {
@Input() id: string;
@Input() text: string;
@Input() items: any[];
constructor() {
}
}
forwardRef
是必需的,因为在声明类之前引用了类 ItemComponent
。
forwardRef
is required because the class ItemComponent
is referenced before it is declared.
这篇关于使用递归数组加载递归组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!