我正在尝试使用递归数组递归加载 Angular 2 组件(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 中所示。如何使我的组件递归迭代以呈现所需的输出?输入数组可以包含任意数量的元素和嵌套。
谢谢!
最佳答案
更新
随着 @NgModule
的引入以及 directives
到 @NgModule
的迁移,forwardRef
不应该不再需要了。
原创
<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
在声明之前被引用。
关于javascript - 使用递归数组递归组件加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38821475/