简体   繁体   中英

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 '\='.<\/i>

export enum Symbols {
  equals = '\u003D'
}
["

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM