如何使用带有 Angular 的字符串数组在 HTML 模板中显示具有 3 列的 table?
How to display a table with 3 columns in HTML template using a array of strings with Angular?
我以数组形式获取数据[ 'one', 'two', 'three', 'four', 'five', 'six']
我想以表格形式显示如下,
<table>
<caption> Numbers:</caption>
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
</tr>
<tr>
<td>four</td>
<td>five</td>
<td>six</td>
</tr>
</table>
上面的模板可以使用 ngFor
& ngIf
动态生成吗?
所以在每个 ( index % 3 ) = 0 处我们将绘制新行但是我们如何在 HTML 中使用 angular 指令来做到这一点?
这里的技巧是传入数组可能有任意数量的字符串。
<table>
<caption> Numbers:</caption>
<ng-container *ngFor="let item of items; let i=index;">
<tr *ngIf="i % 3 == 0">
<ng-container *ngFor="let pos of [1, 2, 3]">
<td *ngIf="i+pos < items.length">{{items[i+pos]}}</td>
</ng-container>
</tr>
</ng-container>
</table>
我还没有测试过,但应该可以。
试试这个(TS 文件):
data = ['one', 'two', 'three', 'four', 'five', 'six'];
results: any[] = [];
constructor() {
this.results = this.groupColumns(this.data);
}
groupColumns(arrays) {
const newRows = [];
for (let index = 0; index < arrays.length; index += 3) {
newRows.push(arrays.slice(index, index + 3));
}
return newRows;
}
在HTML中:
<table>
<caption> Numbers:</caption>
<tr *ngFor="let result of results">
<td>{{result[0]}}</td>
<td>{{result[1]}}</td>
<td>{{result[2]}}</td>
</tr>
</table>
我以数组形式获取数据[ 'one', 'two', 'three', 'four', 'five', 'six']
我想以表格形式显示如下,
<table>
<caption> Numbers:</caption>
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
</tr>
<tr>
<td>four</td>
<td>five</td>
<td>six</td>
</tr>
</table>
上面的模板可以使用 ngFor
& ngIf
动态生成吗?
所以在每个 ( index % 3 ) = 0 处我们将绘制新行但是我们如何在 HTML 中使用 angular 指令来做到这一点?
这里的技巧是传入数组可能有任意数量的字符串。
<table>
<caption> Numbers:</caption>
<ng-container *ngFor="let item of items; let i=index;">
<tr *ngIf="i % 3 == 0">
<ng-container *ngFor="let pos of [1, 2, 3]">
<td *ngIf="i+pos < items.length">{{items[i+pos]}}</td>
</ng-container>
</tr>
</ng-container>
</table>
我还没有测试过,但应该可以。
试试这个(TS 文件):
data = ['one', 'two', 'three', 'four', 'five', 'six'];
results: any[] = [];
constructor() {
this.results = this.groupColumns(this.data);
}
groupColumns(arrays) {
const newRows = [];
for (let index = 0; index < arrays.length; index += 3) {
newRows.push(arrays.slice(index, index + 3));
}
return newRows;
}
在HTML中:
<table>
<caption> Numbers:</caption>
<tr *ngFor="let result of results">
<td>{{result[0]}}</td>
<td>{{result[1]}}</td>
<td>{{result[2]}}</td>
</tr>
</table>