如何在枚举中使用ng-if条件? (angular2 /打字稿)

时间:2016-07-30 19:08:10

标签: angularjs typescript angular enums

我有一个视图,在此视图中有3个按钮:

showListOne()

showListTwo()

showListThree()

当点击每个按钮时,我想在同一视图但不同时呈现不同的列表(一次只显示一个列表,如标签行为)。

所以我想用枚举来做,这就是:

export enum CurrentListView {People,Cars,Places}

@Component({
  selector: 'my-app',
  styles: [require('./my-app.css')],
  directives: [DND_DIRECTIVES],
  providers: [DND_PROVIDERS],
  template: require('./my-app.component.html')
})

  @Injectable()
  export class AppCmp implements OnInit {

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

    currentListView: CurrentListView;

    constructor(private _MyService: MyService) {
    };

    public showListOfPeopleData(): void {
      this.currentListView = CurrentListView.People;
    }

    public showListOfCarsData(): void {
      this.currentListView = CurrentListView.Cars;
    }

    public showListOfPlacesData(): void {
      this.currentListView = CurrentListView.Places;
    }

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

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

      this._MyService.getListOfPlacesData().subscribe(res => {
        this.listOfPlaces = res;
      });
    }
  }

现在,如何使用ng-if询问currentListView的状态?这是我的观点(如果有我尝试的东西并且它有效的话):

<div *ngIf="currentListView == CurrentListView.People">
    <div dnd-sortable-container [dropZones]="['zone-one']" [sortableData]="listOfPeople">
      <div class="list-bg" *ngFor="#person of listOfPeople; #i = index" dnd-sortable [sortableIndex]="i">
        ID: {{person.id}} <p></p> Age: {{person.age}}
      </div>
    </div>
  </div>

<div *ngIf="currentListView == CurrentListView.Cars">
    <div dnd-sortable-container [dropZones]="['zone-one']" [sortableData]="listOfCars">
      <div class="list-bg" *ngFor="#car of listOfCars; #i = index" dnd-sortable [sortableIndex]="i">
        ID: {{car.id}} <p></p> Color: {{car.color}}
      </div>
    </div>
  </div>

<div *ngIf="currentListView == CurrentListView.Places">
    <div dnd-sortable-container [dropZones]="['zone-one']" [sortableData]="listOfPlaces">
      <div class="list-bg" *ngFor="#place of listOfPlaces; #i = index" dnd-sortable [sortableIndex]="i">
        City: {{place.city}} <p></p> Capacity: {{place.capacity}}
      </div>
    </div>
  </div>

我的打字稿或HTML可以更有效吗?我希望看到一个更通用的方法来建议,而不是重复...

感谢分配!

1 个答案:

答案 0 :(得分:0)

我认为你不能比较阵列(不​​管它是不好的表现), 我建议您可以存储&#34;要显示的列表&#34;在一些字符串变量中 像这样的东西:

    currentListView:string = 'Bikes';

就像这个plunkr

一样