2

I'm reviewing this bit of code that is the model for a select filter component for Todos:

    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 }
    ];

It looks as if all of that could be replaced with:

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

So the active filter property would just be typed by the enum VISIBILITY_FILTER and we would loop through then enum in the template like this (Pseudo code):

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

Does that seem reasonable or did I miss something?

Ole
  • 41,793
  • 59
  • 191
  • 359
  • Possible duplicate of [How does one get the names of TypeScript enum entries?](https://stackoverflow.com/questions/18111657/how-does-one-get-the-names-of-typescript-enum-entries) – Damian Chrzanowski Aug 20 '18 at 19:49
  • 1
    I'm certain its not a duplicate, the OP wants to iterate the enum in angular, not get the names. – speciesUnknown Aug 20 '18 at 20:45

1 Answers1

6

try:

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

and

<option *ngFor="let filter of visFilterValues" [ngValue]="filter">{{filter}}</option>
derelict
  • 2,044
  • 10
  • 15