Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

typescript - Select based on enum in Angular2

I have this enum (I'm using TypeScript) :

export enum CountryCodeEnum {
    France = 1,
    Belgium = 2
}

I would like to build a select in my form, with for each option the enum integer value as value, and the enum text as label, like this :

<select>
     <option value="1">France</option>
     <option value="2">Belgium</option>
</select>

How can I do this ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One more solution if you don't want to create a new pipe. You could also extract keys into helper property and use it:

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <select>
        <option *ngFor="let key of keys" [value]="key" [label]="countries[key]"></option>
      </select>
    </div>
  `,
  directives: []
})
export class App {

  countries = CountryCodeEnum

  constructor() {
    this.keys = Object.keys(this.countries).filter(k => !isNaN(Number(k)));
  }
}

Demo: http://plnkr.co/edit/CMFt6Zl7lLYgnHoKKa4E?p=preview

Edit:

if you need the options as numbers instead of strings:

  • replace [value] with [ngValue]
  • add .map(Number) after .filter(...)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...