angularjs - 如何在 ng-if 条件中使用枚举?(angular2/typescript)
我有一个视图,在这个视图中有三个按钮:
showListOne()
showListTwo()
showListThree()
当点击这些按钮中的每一个时,我想在同一个视图中展示不同的列表,但不是同时展示(一次只展示一个列表,就像标签页的行为)。
所以我想用枚举来做,就是这样:
导出枚举 当前列表视图 { 人员, 汽车, 地点 }
@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-if 是我尝试过的,但它不起作用):
<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 能否更高效?我很想看到一个更通用的方法来实现这一点,而不需要重复。
非常感谢!
答案#1
我认为你不能比较数组(更不用说性能很差了),我建议你可以将“要显示的列表”存储在某个字符串变量中,类似这样:
currentListView:string = 'Bikes';
就像在这个 plunkr 中一样
