我正在尝试使用递归数组(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>
我只能在插件中显示第一级输入。如何使我的组件递归迭代以呈现所需的输出?输入数组可以包含任意数量的元素和嵌套。
谢谢!
答案 0 :(得分:0)
我会以这种方式创建你的组件:
@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"
},
(...)
];
}
答案 1 :(得分:0)
<强>更新强>
引入@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
之前会引用它。
答案 2 :(得分:-1)
这是让你开始的东西。您需要自己实现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) {
}