发布于 2026-01-06 0 阅读
0

Angular 组件中枚举的使用简介 枚举示例(面向不熟悉枚举的用户) 如何从枚举中获取字符串数组 结论

在 Angular 组件中使用枚举

引言

对于不熟悉枚举的人来说,这里举个枚举的例子。

如何从枚举类型中获取字符串数组

结论

这是一份关于在 Angular 应用中使用枚举的简短指南。
以下内容将介绍如何操作:

  • component.html在模板中引用枚举
  • *ngFor使用管道遍历枚举keyvalue
  • 使用枚举有条件地显示内容*ngIf
  • 获取枚举的所有值作为参数Array<sting>

引言

如果您只想了解具体细节,可以跳过下一段文字(我尊重您的选择)。

我喜欢在 TypeScript 中使用枚举,因为我是一个记性很差、技术又糟糕的开发者,我 80% 的工作都依赖编辑器的自动补全功能。枚举可以让你避免使用字符串,也省去了记住之前用过哪些字符串值的麻烦。它们还能让你限制属性的值,防止用户随意提交任意值。所以,如果你还没开始使用枚举,那就赶紧开始用吧;如果你已经在用了,那就更要多用,用到极致。成为你想看到的枚举吧!

对于不熟悉枚举的人来说,这里举个枚举的例子。

// This is our PropertyType enum
// We give each value a string value otherwise PropertyType.House would return 0, Property.Apartment would return 1, and so on
enum PropertyType {
  House = 'House',
  Apartment = 'Apartment',
  Flat = 'Flat',
  Studio = 'Studio'
}

// Our class which has a 'type' property.
// We want to lock type down to a set of predefined values
class Property {
  constructor(
    public monthlyPrice: number,
    public type: PropertyType
  ) { }
}

// Creates a property successfully
const property = new Property(1250, PropertyType.Apartment);

// Will display an error from our linter and in the Angular CLI
const property = new Property(1250, PropertyType.RANDOM_VALUE);

Enter fullscreen mode Exit fullscreen mode

枚举可以在 Angular 模板中使用。这在诸如避免为下拉菜单硬编码值或根据组件状态显示不同内容等情况下非常有用。在我看来,它与响应式表单配合得非常好。
要在 Angular 模板中访问枚举,您需要先将其存储在 component.ts 文件中的变量中。在本例中,我们将创建一个简单的响应式表单来生成一个枚举。Property

// Declaring our Enum. The Enum could also be imported from another file if needed 
enum PropertyType {
  House = 'House',
  Apartment = 'Apartment',
  Flat = 'Flat',
  Studio = 'Studio'
}

@Component({
  selector: 'app-property-component',
  templateUrl: './property.component.html'
})
export class PropertyComponent{

  // Make a variable reference to our Enum
  ePropertyType = PropertyType;

  // Build our form
  form: FormGroup;
  type: FormControl;
  price: FormControl; // This is only here to make the form look more l3g1t

  constructor(private formBuilder: FormBuilder){
    this.form = this.formBuilder.group({
      type: [null, [Validators.required]],
      price: [0, [Validators.required]]
    });

    this.type = this.form.controls.type as FormControl;
    this.price = this.form.controls.price as FormControl;
  }
}
Enter fullscreen mode Exit fullscreen mode

然后,在我们的property.html模板中,我们可以按如下方式使用枚举。我们将使用管道keyvalue符。这会将我们的PropertyType枚举(引用为 `Enum` ePropertyType)转换为KeyValue数组,我们可以使用 `Array` 遍历该数组*ngFor。由于我们声明枚举时PropertyType使用了字符串值(例如 `Enum` Apartment = 'Apartment'),因此 `Array`KeyValue.key和`Array`KeyValue.value都将包含枚举的字符串值,所以我们可以使用其中任何一个。

然后,我们可以将枚举作为*ngIf条件的一部分来显示消息。

<form [formGroup]="form">
  <!-- Property type form control -->
  <label for="propertyType">Property Type</label>
  <select id="propertyType" [formControl]="type">
    <option [ngValue]="null">Select one...</option>
    <option *ngFor="let type of ePropertyType | keyvalue" [ngValue]="type.value">{{type.value}}</option>
  </select>

  <!-- Property price form control -->
  <label for="propertyPrice">Property Price</label>
  <input id="propertyPrice" class="form-control" type="number" [formControl]="price" placeholder="Street...">

</form>

<!-- Conditionally display a message if a certain PropertyType is selected (or not selected) -->
<ng-container *ngIf="type.value !== ePropertyType.House">
Wouldn't you prefer a nice garden?
</ng-container>
Enter fullscreen mode Exit fullscreen mode

如何从枚举类型中获取字符串数组

从枚举类型中获取字符串数组string[]或者Array<string>如果你像我一样是个酷小子,也可以用字符串数组)的一个巧妙小技巧是使用 `use`Object.keys和 `and`。Array.filter

// Declare your enum
enum PropertyType {
  House = 'House',
  Apartment = 'Apartment',
  Flat = 'Flat',
  Studio = 'Studio'
}

/* Get an array of keys, filtering out number values
*  as the enum object itself is as follows
*  { 0: 'House', 1: 'Apartment' ...}
*/
const propertyType: Array<string> = Object.keys(PropertyType).filter(key => isNaN(+key));
Enter fullscreen mode Exit fullscreen mode

结论

枚举类型很受欢迎,应该多多使用。

文章来源:https://dev.to/shane/working-with-enums-in-angular-html-templates-2io9