【问题标题】:How to use ng-if condition with enums? (angular2/typescript)如何在枚举中使用 ng-if 条件? (角度2/打字稿)
【发布时间】:2016-12-05 06:41:21
【问题描述】:

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

showListOne()

showListTwo()

showListThree()

当每个按钮被点击时,我想在同一个视图中显示一个不同的列表,但不是在同一时间(一次只会显示一个列表,就像标签行为一样)。

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

导出枚举 CurrentListView {人物、汽车、地点}

@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 的状态是什么?这是我的观点(ng-如果我尝试过并且它不起作用):

<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>

我的 typescript 或 html 可以更高效吗?我很想看到一个更通用的方法来做到这一点而无需重复的建议..

感谢分配!

【问题讨论】:

  • 我建议以不同的方式进行。将每个视图放入一个组件中,然后为每个视图设置路由。您的按钮成为加载相应组件的路由器链接。

标签: angularjs typescript angular enums


【解决方案1】:

我不认为你可以比较数组(别管它是糟糕的表现), 我建议您可以将“要显示的列表”存储在某个字符串变量中 像这样:

    currentListView:string = 'Bikes';

喜欢这个plunkr

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 2018-09-16
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 2019-06-04
    • 2020-01-17
    相关资源
    最近更新 更多