以这种方式显示一些动态嵌套数据的最佳方法是什么?
const data = [
{ name: 'Paul', children: [
{ name: 'John'},
{ name: 'Rachel', children: [
{ name: 'Abraham' },
{ name: 'Diana' },
{ name: 'Sara', children: [
{ name: 'Johan' }
]}
]},
{ name: 'George', children: [
{ name: 'Stewart' }
]},
{ name: 'Andrew' }
]},
{ name: 'Richard' }
];
结果应为:
答案 0 :(得分:3)
这是工作中的blitz
您可以按照以下步骤创建组件
此组件的作用是获取一个数组并将其显示在li
中,然后使用children
再次调用自身
list.component.ts
@Component({
selector: 'list',
template: `
<ul *ngIf="data">
<li *ngFor="let row of data">
{{row.name}}
<list [data]="row.children"></list>
</li>
</ul>
`,
})
export class ListComponent {
@Input() data: any[];
}
app.component.ts
@Component({
selector: 'my-app',
template: '<list [data]="data"></list>',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
data = [
{ name: 'Paul', children: [
{ name: 'John'},
{ name: 'Rachel', children: [
{ name: 'Abraham' },
{ name: 'Diana' },
{ name: 'Sara', children: [
{ name: 'Johan' }
]}
]},
{ name: 'George', children: [
{ name: 'Stewart' }
]},
{ name: 'Andrew' }
]},
{ name: 'Richard' }
];
}