Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 796
FrankTheTank Avatar asked Sep 11 '25 07:09

FrankTheTank


1 Answers

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;
}
like image 57
acdcjunior Avatar answered Sep 13 '25 02:09

acdcjunior