我想在 Angular 2 中构建一个表。
这张表应该是这样的
我有一个组件
,它给我一个数据
export class ResultsComponent implements OnInit {
public items: any;
ngOnInit() {
this.items = ['app1', 'item1', 'item2', 'item3', 'app2', 'item4',
'item5', 'item6', 'app3', 'item7', 'item8', 'item9'];
this.buildArr(this.items);
}
buildArr(theArr: any[]) {
const arrOfarr = [];
for (let i = 0; i < theArr.length ; i += 4) {
const row = [];
for (let j = 0; j < 4; j++) {
const value = theArr[i + j];
if (!value) {
break;
}
row.push(value);
}
arrOfarr.push(row);
}
return arrOfarr;
}
这是我的模板
<h1>Results</h1>
<table class="table" id="myTable" class="table">
<thead>
<tr>
<th></th>
<th>Part 1</th>
<th>Part 2</th>
<th>Part 3</th>
<th>Part 4</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of buildArr(items);let i = index">
<td *ngFor="let item of row">{{item}}</td>
</tr>
</tbody>
</table>
但这是我得到的
我怎样才能得到我需要的表格? 我怎样才能插入包含消息“不存在!”的表格单元格?
最佳答案
您只需要用“不存在”文本填写每一行的其余部分。如果您可以将元素数组转换为列表,肯定有更优化的方法来执行此操作对象或 map 。
下面显示的是对现有代码的一个小改动,用“不存在”文本填充索引
export class ResultsComponent implements OnInit {
public items: any;
ngOnInit() {
this.items = ['app1', 'item1', 'item2', 'item3', 'app2', 'item4',
'item5', 'item6', 'app3', 'item7', 'item8', 'item9'
];
this.buildArr(this.items);
}
buildArr(theArr: any[]) {
const arrOfarr = [];
for (let i = 0; i < theArr.length; i += 4) {
const row = [];
for (let j = 0; j < 4; j++) {
const value = theArr[i + j];
if (j > 0 && value.substring(0, 2) == "app") { //make sure to skip first item
while (j < 4) { //finish off row with placeholder string
row[j] = "does not exist"
}
break;
}
row.push(value);
}
arrOfarr.push(row);
}
return arrOfarr;
}
<h1>Results</h1>
<table class="table" id="myTable" class="table">
<thead>
<tr>
<th></th>
<th>Part 1</th>
<th>Part 2</th>
<th>Part 3</th>
<th>Part 4</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of buildArr(items);let i = index">
<td *ngFor="let item of row">{{item}}</td>
</tr>
</tbody>
</table>
关于javascript - Angular 2 中的表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45843138/