Angular5:使用* ngFor迭代枚举

问题描述 投票:3回答:1

我正在尝试创建一种具有键值对的结构,其中键是'equals'之类的标识符,值是类似于'\ u003D'的unicode等效html。现在我正在使用枚举,但我不确定这是否是最好的结构。无论如何,我需要使用这个枚举(或其他结构)在页面的下拉列表中显示unicode字符,方法是使用ngFor语句迭代我的枚举并创建innerHtml与unicode字符对应的选项。做这个的最好方式是什么?

现在我的代码如下:

枚举

export enum Symbols {
  equals = '\u003D'
}

component.ts

symbols: Symbols;

component.html

<select *ngFor="let symbol of symbols">
     <option value="and">{{symbol}}</option>
</select>
angular typescript enums ngfor
1个回答
10
投票

要在组件中访问枚举,您必须声明属性,就像您所做的那样,但不应声明类型为Symbols(使用:),而应将Symbol分配给它(使用=)。

要声明带有选项的<select>,你应该在*ngFors中使用<option>,而不是在<select>中。

另外,要迭代枚举,必须使用Object.keys(symbols)keys(symbol)在下面的模板中使用别名。

Stackblitz Demo here.

import { Component } from '@angular/core';

export enum Symbols {
  equals = '\u003D',
  notEquals = '!='
}

@Component({
  selector: 'my-app',
  template: `
    <p>
      Having the name as label and symbol as value:
      <select>
        <option *ngFor="let symbol of keys(symbols)" [ngValue]="symbols[symbol]">{{symbol}}</option>
      </select>
    </p>
    <p>
      Having the symbol as label and name as value:
      <select>
        <option *ngFor="let symbol of keys(symbols)" [ngValue]="symbol">{{symbols[symbol]}}</option>
      </select>
    </p>
  `
})
export class AppComponent  {
  keys = Object.keys;
  symbols = Symbols;
}
© www.soinside.com 2019 - 2024. All rights reserved.