📌  相关文章
📜  如何使用 ngfor 从数组中创建 Angular 下拉列表?(1)

📅  最后修改于: 2023-12-03 15:23:56.483000             🧑  作者: Mango

如何使用 ngFor 从数组中创建 Angular 下拉列表?

在 Angular 中创建下拉列表通常涉及到循环,通常使用 ngFor 指令从数组中循环创建下拉选项。下面我们将介绍创建下拉列表所需的基本步骤。

第一步:定义下拉选项数组

要创建下拉列表,必须先定义一个包含选项的数组。 在下面的示例中,我们创建一个选项数组,它包含颜色名称。

colors = ['Red', 'Green', 'Blue', 'Yellow'];
第二步:使用 ngFor 创建下拉列表

使用 ngFor 指令循环显示选项。

<select>
  <option *ngFor="let c of colors">{{c}}</option>
</select>

在上述示例中,我们使用 ngFor 指令从颜色数组中循环创建选项。 我们使用 let c of colors 语法将每个数组元素存储在变量 c 中,并使用双花括号语法显示值。

完整代码:
<!-- app.component.html -->
<select>
  <option *ngFor="let c of colors">{{c}}</option>
</select>
// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  colors = ['Red', 'Green', 'Blue', 'Yellow'];
}

这是一个简单的 Angular 下拉列表,它通过循环从数组中创建选项。 通过这个例子,您可以学习如何使用 ngFor 指令从数组中创建下拉列表。