Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

angular - Pass enums in angular2 view templates

Can we use enums in an angular2 view template?

<div class="Dropdown" dropdownType="instrument"></div>

passes the string as input:

enum DropdownType {
    instrument,
    account,
    currency
}

@Component({
    selector: '[.Dropdown]',
})
export class Dropdown {

    @Input() public set dropdownType(value: any) {

        console.log(value);
    };
}

But how to pass an enum configuration? I want something like this in the template:

<div class="Dropdown" dropdownType="DropdownType.instrument"></div>

What would be the best practice?

Edited: Created an example:

import {bootstrap} from 'angular2/platform/browser';
import {Component, View, Input} from 'angular2/core';

export enum DropdownType {

    instrument = 0,
    account = 1,
    currency = 2
}

@Component({selector: '[.Dropdown]',})
@View({template: ''})
export class Dropdown {

    public dropdownTypes = DropdownType;

    @Input() public set dropdownType(value: any) {console.log(`-- dropdownType: ${value}`);};
    constructor() {console.log('-- Dropdown ready --');}
}

@Component({ selector: 'header' })
@View({ template: '<div class="Dropdown" dropdownType="dropdownTypes.instrument"> </div>', directives: [Dropdown] })
class Header {}

@Component({ selector: 'my-app' })
@View({ template: '<header></header>', directives: [Header] })
class Tester {}

bootstrap(Tester);
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Create an Enum:

enum ACTIVE_OPTIONS {
  HOME = 0,
  USERS = 1,
  PLAYERS = 2
}

Create a component, be sure your enum list will have the typeof:

export class AppComponent {
  ACTIVE_OPTIONS = ACTIVE_OPTIONS;
  active: ACTIVE_OPTIONS;
}

Create a template:

<li [ngClass]="{ 'active': active === ACTIVE_OPTIONS.HOME }">
  <a routerLink="/in">
    <i class="fa fa-fw fa-dashboard"></i> Home
  </a>
</li>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...