FrankTheTank
FrankTheTank

Reputation: 785

Angular5: Iterate Over Enum Using *ngFor

I am trying to make a structure of some sort that has key value pairs where the key is an identifier like 'equals' and the values are the unicode equivalent html like '\u003D'. Right now I am using an enum, but I am not sure if this is the best structure. Anyways, I need to use this enum (or other structure) to display the unicode characters in a drop down on a page by using a ngFor statement to iterate over my enum and making options which innerHtml correspondes to the unicode character. What is the best way to do this?

Right now my code is as follows:

enum

export enum Symbols {
  equals = '\u003D'
}

component.ts

symbols: Symbols;

component.html

<select *ngFor="let symbol of symbols">
     <option value="and">{{symbol}}</option>
</select>

Upvotes: 4

Views: 9790

Answers (2)

Stanza Arrow
Stanza Arrow

Reputation: 11

You can also use the keyvalue pipe as well, it makes your life easier.

<p *ngFor="let enum of TestEnum | keyvalue">
  {{ enum.key }} - {{ enum.value}}
</p>

Upvotes: 1

acdcjunior
acdcjunior

Reputation: 135862

To have the enum accessible within the component, you must declare a property, like you did, but instead of declaring it of type Symbols (using :), you should assign Symbol to it (using =).

To declare a <select> with options, you should use the *ngFor in the <option>s, not in the <select>.

Also, to iterate the enum, you must use Object.keys(symbols), which is aliased by keys(symbol) in the template below.

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

Upvotes: 15

Related Questions