从html发送时,TypeScript 2+中的枚举失去了价值

时间:2018-05-26 18:20:52

标签: angular typescript

我有一个像这样定义的对象和枚举:

<svg viewBox="0 0 100 100" fill="none" stroke="black" stroke-width="1">
		<path d="M 1,35 75,35 75,25 99,50 75,75 75,65 1,65z" />	
</svg>

<hr>

<svg viewBox="0 0 100 100" fill="green" stroke="blue" stroke-width="2">
		<path d="M 1,35 75,35 75,25 99,50 75,75 75,65 1,65z" />	
</svg>

我在我的组件中使用此枚举:

export interface Character {
  name: string;
  side: Side;
}

export enum Side {
  All,
  Light,
  Dark
}

我的HTML看起来像这样。问题在于(点击)事件。我将这样的枚举传递给我的组件,不幸的是我的组件将其解析为字符串。

import { Component, OnInit } from '@angular/core';
import { Character, Side } from '../core';

@Component({
  selector: 'app-tabs',
  templateUrl: './tabs.component.html'
})
export class TabsComponent {
  chosenList = Side.All; // initial value set to 0

  characters = [
    { name: 'Luke Skywalker', side: Side.All }, // side is set to 0
    { name: 'Darth Vader', side: Side.All } // side is set to 0
  ];

  onChoose(side: Side): void {
    this.chosenList = side; // this line goes wrong set chosenList to string 'Side.All'
  }

  getCharacters(): Character[] {
    if (this.chosenList === Side.All) {
      return this.characters.slice();
    }
    return this.characters.filter((character) => {
      return character.side === this.chosenList;
    });
  }

  onSideChosen(charInfo: Character): void {
    const pos = this.characters.findIndex((char) => {
      return char.name === charInfo.name;
    });
    this.characters[pos].side = charInfo.side;
  }
}

问题是当我点击按钮&#34;所有按钮&#34;这行代码被调用

<div id="tab-main" class="container">
  <ul class="nav nav-tabs">
    <li class="nav-item">
      <a [ngClass]="{active: chosenList === 'Side.All'}" class="nav-link" (click)="onChoose('Side.All')" style="cursor: pointer">All</a>
    </li>
    <li class="nav-item">
      <a [ngClass]="{active: chosenList === 'Side.Light'}" class="nav-link" (click)="onChoose('Side.Light')" style="cursor: pointer">Light</a>
    </li>
    <li class="nav-item">
      <a [ngClass]="{active: chosenList === 'Side.Dark'}" class="nav-link" (click)="onChoose('Side.Dark')" style="cursor: pointer">Dark</a>
    </li>
  </ul>
  <app-list [characters]="getCharacters()" (sideAssigned)="onSideChosen($event)"></app-list>
</div>

然而,当我比较像这样的值时

onChoose(side: Side): void {
    this.chosenList = side; // this line goes wrong set chosenList to string 'Side.All'
  }

它总是返回false,因为selectedList不再是enum,而是它的字符串。

我的问题是如何将 .html 文件中的枚举传递给 .ts 我知道我可以通过在html中发送0/1/2来解决这个问题但是这样我就失去了可读性......

1 个答案:

答案 0 :(得分:2)

  1. 在组件
  2. 中声明字段变量public Side = Side;
  3. 从定义的文件
  4. 导入Side
  5. 将模板引用更改为"{active: chosenList === Side.All}"
  6. 问题基本上是在模板中你无权访问组件外部定义的东西,特别是如果必须首先编译它