【问题标题】:Angular 4. How to print 2d array using html/typescript?Angular 4. 如何使用 html/typescript 打印二维数组?
【发布时间】:2017-10-05 07:17:51
【问题描述】:
【问题讨论】:
标签:
html
angular
typescript
multidimensional-array
【解决方案1】:
继续 Mike 的回答。
根据您实现二维数组的方式/您的意图,您也可以这样做:
// Declare a two dimensional array
public data: any[][] = [];
// Checks to see if the array contains the element, if it does then add it, otherwise initialise a new element and then assign the object to it.
if (!this.data['item']) {
this.data['item'] = [];
this.data['item']['sub-item'] = {date: '2019-01-01', value: 0};
} else {
this.data['item']['sub-item'] = {date: '2019-01-01', value: 0};
}
在 html 模板中,您可以通过键值管道使用嵌套 for 循环来遍历键值和值:
<div *ngFor="let i of data| keyvalue">
{{i.key}}
<ng-container *ngFor="let j of i.value | keyvalue">
{{j.value.date}}
{{j.value.value}}
</ng-container>
</div>
结果将是:
2019-01-01 0
【解决方案2】:
取决于您要做什么,但这里是一个基本示例。
假设您在组件中定义了一个变量:
public items: any[][];
constructor() {
this.items = [
[1, 2],
[3, 4],
[5, 6]
];
}
然后在你的模板中你可以使用嵌套的*ngFor:
<div *ngFor="let i of items">
<span *ngFor="let j of i">
{{j}}
</span>
</div>
输出:
1 2
3 4
5 6
根据您的用例调整它。