【问题标题】:Fail to use enum properly with ngSwitchngSwitch 无法正确使用枚举
【发布时间】:2023-04-11 10:19:01
【问题描述】:

我有三个按钮显示三个不同的列表,所以我想添加 enums 来帮助我决定使用 ngSwitch 显示哪个列表,但我遇到了一个错误。

这是打字稿:

export enum ListType {People, Cars}

export class AppCmp implements OnInit {

    listOfPeople: Person[];
    listOfCars: Car[];

    currentListView: CurrentListView;

    constructor(private _MyService: MyService) {
    };


    public setListType(type: ListType) {
        this.listType = type;
    }

    ngOnInit() {
      this._MyService.getListOfPeopleData().subscribe(res => {
        this.listOfPeople = res;
      });

      this._MyService.getListOfCarsData().subscribe(res => {
        this.listOfCars = res;
      });
    }
}

这是 HTML:

<div>
  <button md-button
          (click)="setListType(listType.People)"
          class="md-primary">People
  </button>

  <button md-button
          (click)="setListType(listType.Cars)"
          class="md-primary">Cars
  </button>
</div>


<md-content>

  <h1 align="center">{{title}}</h1>

  <div [ngSwitch]="currentListView">

    <div *ngSwitchCase="listType.People">
        <div class="list-bg" *ngFor="#person of listOfPeople">
          ID: {{person.id}} <p></p> name:{{person.name}}
        </div>
      </div>
    </div>
    <div *ngSwitchCase="listType.Cars">
        <div class="list-bg" *ngFor="#car of listOfCars;>
          ID: {{car.id}} <p></p> color: {{car.color}}
        </div>
    </div>

  </div>

</md-content>

我在这里做错了什么?

错误是:

EXCEPTION: Error: Uncaught (in promise): Template parse errors: Can't
bind to 'ngSwitchCase' since it isn't a known native property ("  
  <div [ngSwitch]="currentListView">

     <div [ERROR ->]*ngSwitchCase="listType.People"> Property binding ngSwitchCase not used
by any directive on an embedded template ("  
  <div [ngSwitch]="currentListView">

我正在使用 Typescript 和 Angular2。

【问题讨论】:

  • 错误是什么?
  • @JCorcuera 添加了错误,抱歉
  • 不应该是export enum ListType {People, Cars}吗?
  • 是的,我改了,没用……
  • *ngFor="#car of listOfCars;&gt; 在此末尾缺少"。应该是 ...*ngFor="#car of listOfCars;"&gt;

标签: javascript angularjs typescript angular enums


【解决方案1】:

考虑到enum

export enum ListType {People, Cars}

如果你想在模板中使用它,比如:

...
<div *ngSwitchCase="listType.People">
...

您必须通过在您的类中创建一个属性来make the enum available to your component,该属性将充当enum 的“别名”(在该模板中),如下所示:

export class AppCmp implements OnInit {

  public listType = ListType;  // <-- a prop with the name you want to use for the enum
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-18
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多