【发布时间】:2017-05-17 10:57:04
【问题描述】:
我正在尝试动态创建表格的元素,但我有疑问。
如何创建新的<tr>,例如每个 4 个<td>,然后继续创建新的<td>
<table>
<tr>
<td class="category-card" *ngFor= "let category of categories">
<img class="product-card-image" src="{{category.icon}}">
<span class="barImage">{{category.title}}</span>
</td>
</table>
编辑:
<table>
<ng-template *ngFor="let category of categories; let i = index">
<tr *ngIf="(i % 4) == 0">
<td class="product-card">
<img class="product-card-image" src="/app/assets/img/{{category.icon}}.png">
<span class="barImage">{{category.titulo}}</span>
</td>
</tr>
</ng-template>
</table>
EDIT2: 我添加了
<table [outerHTML]="categorias | dynamicTablePipe"></table> on my html
这是一个外部类(我在 NGModule 上声明过)
@Pipe({
name: 'dynamicTablePipe'
})
export class DynamicTablePipe implements PipeTransform{
transform(contents) {
let template = ``;
let index = 0;
for (let content of contents) {
let currentTemplate = ``;
if (index === 0) {
// check if first record
currentTemplate = `
<tr>
<td class="product-card">
<img class="product-card-image" src="/app/assets/img/${content.icono}.png">
<span class="barImage">${content.titulo}</span>
</td>`;
} else if ((index % 4) === 0) {
// check if multiple of 4
currentTemplate = `
</tr>
<tr>
<td class="product-card">
<img class="product-card-image" src="/app/assets/img/${content.icono}.png">
<span class="barImage">${content.titulo}</span>
</td>`;
} else {
// normal row
currentTemplate = `
<td class="product-card">
<img class="product-card-image" src="/app/assets/img/${content.icono}.png">
<span class="barImage">${content.titulo}</span>
</td>`;
}
index++;
template += currentTemplate;
}
return template;
}
}
管道内的代码工作正常,这是最后形成的模板字符串:
<tr>
<td class="product-card">
<img class="product-card-image" src="/app/assets/img/smartphone.png">
<span class="barImage">Telefonia</span>
</td>
<td class="product-card">
<img class="product-card-image" src="/app/assets/img/gamepad.png">
<span class="barImage">Videojuegos</span>
</td>
<td class="product-card">
<img class="product-card-image" src="/app/assets/img/laptop.png">
<span class="barImage">Portatiles</span>
</td>
<td class="product-card">
<img class="product-card-image" src="/app/assets/img/speaker.png">
<span class="barImage">Reproductores</span>
</td>
</tr>
<tr>
<td class="product-card">
<img class="product-card-image" src="/app/assets/img/link.png">
<span class="barImage">Redes</span>
</td></tr>
问题出在回归的那一刻
谢谢
【问题讨论】:
-
"跳转到一个新文件" ---> whaaaat ?
-
大声笑,对不起。我的意思是,我怎样才能每 4 个单元格创建一个新的表格行,然后继续将单元格添加到这个新行中
-
老实说,“每行有 4 个元素”听起来应该在 CSS 中执行,而不是在标记中执行
-
@PeterT 如何通过 CSS 限制表格的 os 列/单元格的数量?
-
@Hanzo 我建议您不要使用
<table>,而只是使用一串元素,然后使用 css 进行布局。是这样的:Fiddle link(应该说我是个css菜鸟,所以还有很大的提升空间)