我有如下对象列表:
cases: Case[] = [
{ id: 1, name: 'A' },
{ id: 1, name: 'B' },
{ id: 1, name: 'C' },
{ id: 1, name: 'D' },
{ id: 1, name: 'E' },
{ id: 1, name: 'F' },
];
我想在ngFor指令中将其显示为4列
<li *ngFor="let row of casesRows; index as i;">
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">{{i}}</h5>
</div>
</div>
</li>
我被Typescript转换为4列列表所困扰。 我的第一个想法是:
ngOnInit() {
this.getCasesRows();
}
getCasesRows() {
this.i = 0;
this.cases.forEach(element => {
console.log(element)
if (this.i = 0 ) {
this.cases4.col1 = element;
} else if (this.i = 1) {
this.cases4.col2 = element;
} else if (this.i = 2) {
this.cases4.col3 = element;
} else if (this.i = 3) {
this.cases4.col4 = element;
this.i = -1;
}
this.i = this.i + 1;
});
}
但是我最终遇到了如下错误: 错误TypeError:“ _ this.cases4未定义”
预期的输出:这样显示4列:
A B C D
E F
作为卡片
答案 0 :(得分:1)
您需要像array_chunk这样的示例:
var cases = [
{ id: 1, name: 'A' },
{ id: 1, name: 'B' },
{ id: 1, name: 'C' },
{ id: 1, name: 'D' },
{ id: 1, name: 'E' },
{ id: 1, name: 'F' },
];
function array_chunk(arr, len) {
var chunks = [],
i = 0,
n = arr.length;
while (i < n) {
chunks.push(arr.slice(i, i += len));
}
return chunks;
}
console.log(array_chunk(cases, 4));
答案 1 :(得分:0)
尝试一下。
ts
<div class="container">
<div class="wrapper">
<div class="toggle"><a href="javascript:void"><i class="toggle-icon fas fa-cogs"></i></a></div>
<div class="toggle-content">
<p>Some content</p>
</div>
</div>
</div>
html
const cases = [
{ id: 1, name: 'A' },
{ id: 1, name: 'B' },
{ id: 1, name: 'C' },
{ id: 1, name: 'D' },
{ id: 1, name: 'E' },
{ id: 1, name: 'F' },
];
答案 2 :(得分:-1)
尝试此操作以消除您的错误。
var cases4 = {};
var i = 1;
this.cases.forEach(element => {
cases4["col"+i++] = element.name;
});
答案 3 :(得分:-2)