我正在尝试用递归数组(plunk: http://plnkr.co/edit/3npsad?p=preview)递归加载Angular 2组件。
给定这个递归数组:
[
{
"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所示。我如何使我的组件递归迭代以呈现所需的输出?输入数组可以包含任意数量的元素和嵌套。
谢谢!
update
随着@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
类在声明之前被引用。
我将这样创建您的组件:
@Component({
selector: 'my-item',
template: `
<div id="data.id" text="data.def"></div>
<my-item *ngFor="let item of items" [data]="item"></my-item>
`
})
export class MyItemComponent {
@Input() data: any;
}
,并将其称为另一个组件中的组件,并提供整个组件数据:
@Component({
selector: 'other-comp',
template: `
<my-item [data]="data" *ngFor="let data of wholeData"></my-item>
`
})
export class OtherComponent {
wholeData = [
{
"id": 1,
"text": "abc"
},
(...)
];
}
这里有一些东西可以让你开始。您需要自己实现HTML返回函数:
var a = [
{
"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"
}
]
}
];
function iterateRecursive(array) {
for(var i = 0; i < array.length; i++) {
if(array[i].items) {
console.log(array[i].text);
//uncomment: printHtml(array[i].id, array[i].text);
iterateRecursive(array[i].items)
} else {
console.log(array[i].text);
}
}
}
iterateRecursive(a);
//implement this function that takes an id and text and returns html
//call it in place of console log
function printHtml(id, text) {
}