[英]How to use ngIfThen with ng-container
我正在构建一个简单的石头剪刀布应用程序。 当我点击一个按钮(石头/纸/剪刀)时,它会说:“你选了……”。 之后它应该隐藏其他2个按钮。
我想选择隐藏整个 ng-container 的选项。 单击其中一个按钮后,有没有办法隐藏 ng-container? 那么将它添加到 *ngIfThen 语句中?
<div *ngIf="hand==='rock' then rockTemplate"></div>
<div *ngIf="hand==='paper' then paperTemplate"></div>
<div *ngIf="hand==='scissors' then scissorTemplate"></div>
<ng-template #rockTemplate>
You picked: <app-rock></app-rock>
</ng-template>
<ng-template #paperTemplate>
You picked: <app-paper></app-paper>
</ng-template>
<ng-template #scissorTemplate>
You picked: <app-scissors></app-scissors>
</ng-template>
<ng-container #hideContainer class="board">
<app-rock (click)="pickHand('rock')"></app-rock>
<app-paper (click)="pickHand('paper')"></app-paper>
<app-scissors (click)="pickHand('scissors')"></app-scissors>
</ng-container>
我认为您可以使用ng-switch
进行简化:
<div [ngSwitch]="hand">
<div *ngSwitchCase="rock">You picked: <app-rock></app-rock></div>
<div *ngSwitchCase="paper">You picked: <app-paper></app-paper></div>
<div *ngSwitchCase="scissors">You picked: <app-scissors></app-scissors>
</div>
<ng-container *ngIf="!hasSelection" class="board">
<app-rock (click)="pickHand('rock')"></app-rock>
<app-paper (click)="pickHand('paper')"></app-paper>
<app-scissors (click)="pickHand('scissors')"></app-scissors>
</ng-container>
// In your component class
hasSelection: boolean;
hand: 'rock' | 'scissors' | 'paper';
// ...
pickHand(type: 'rock' | 'scissors' | 'paper') {
this.hasSelection = true;
this.hand = type;
}
使用ng-switch
您的模板看起来更清晰、更易于阅读。 您可以通过布尔变量显示/隐藏ng-container
,一旦用户选择一种手型,该变量就会切换。
我不知道你的逻辑,但你必须重新启用ng-container
,如果用户有可能再次选择一手牌。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.