Angular的循环模板可以遍历枚举吗?

时间:2018-08-20 19:45:37

标签: javascript angular typescript

我正在Todo内查看此bit of code that is the model for a select filter component

    export enum VISIBILITY_FILTER {
      SHOW_COMPLETED = 'SHOW_COMPLETED',
      SHOW_ACTIVE = 'SHOW_ACTIVE',
      SHOW_ALL = 'SHOW_ALL'
    }

    export type TodoFilter = {
      label: string;
      value: VISIBILITY_FILTER;
    };

    export const initialFilters: TodoFilter[] = [
      { label: 'All', value: VISIBILITY_FILTER.SHOW_ALL },
      { label: 'Completed', value: VISIBILITY_FILTER.SHOW_COMPLETED },
      { label: 'Active', value: VISIBILITY_FILTER.SHOW_ACTIVE }
    ];

似乎所有这些都可以替换为:

export enum VISIBILITY_FILTER {
  SHOW_COMPLETED = 'Completed',
  SHOW_ACTIVE = 'Active',
  SHOW_ALL = 'All'
}

因此,active过滤器属性将仅由枚举VISIBILITY_FILTER键入,我们将在模板中依次遍历枚举,如下所示(伪代码):

    <option *ngFor="let filter of VISIBILITY_FILTER;" [ngValue]="filter">{{VISIBILITY_FILTER[VISIBILITY_FILTER.filter]}}
    </option>

这看起来合理还是我错过了什么?

1 个答案:

答案 0 :(得分:4)

尝试:

public get visFilterValues() {
  return Object.keys(VISIBILITY_FILTER).map(k => VISIBILITY_FILTER[k]);
}

<option *ngFor="let filter of visFilterValues" [ngValue]="filter">{{filter}}</option>