ngFor 是一个 for 循环,只能用于循环遍历 list,不能用于遍历单个实体。
下图中的 pokemons 通常是数据库中的数据:

例子:
app.components.ts:
// 使用类型检查
interface Pokemon {
id: number;
name: string;
type: string;
// isCool: boolean;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
pokemons: Pokemon[] = [
{
id: 1,
name: 'pikachu',
type: 'electric',
},
{
id: 2,
name: 'squirtle',
type: 'water',
},
{
id: 3,
name: 'charmander',
type: 'fire',
},
];
constructor() {}
}
app.component.html:
<table>
<thead>
<th>Index</th>
<th>Name</th>
<th>Type</th>
</thead>
<tbody>
<tr *ngFor="let pokemon of pokemons; let i = index">
<td>{{ i }}</td>
<td>{{ pokemon.name }}</td>
<td>{{ pokemon.type }}</td>
</tr>
</tbody>
</table>
Web 页面:

本文解释了Angular中ngFor循环的用法,展示了如何在typescript中定义接口并用ngFor遍历pokemons列表,展示了如何在Web页面上显示动态数据。

276

被折叠的 条评论
为什么被折叠?



