Ole
Ole

Reputation: 47212

Can Angular's template for loop loop through an enum?

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?

Upvotes: 2

Views: 224

Answers (1)

derelict
derelict

Reputation: 2080

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>

Upvotes: 6

Related Questions