简体   繁体   English

如何在 ng-container 中使用 ngIfThen

[英]How to use ngIfThen with ng-container

I'm building a simple rock, paper, scissors app.我正在构建一个简单的石头剪刀布应用程序。 The moment I click a button (rock/paper/scissor), it will say: "You picked ... ".当我点击一个按钮(石头/纸/剪刀)时,它会说:“你选了……”。 After that it should hide the other 2 buttons.之后它应该隐藏其他2个按钮。

I want to go for the option to hide the whole ng-container.我想选择隐藏整个 ng-container 的选项。 Is there a way I can hide the ng-container after clicking on one of the buttons?单击其中一个按钮后,有没有办法隐藏 ng-container? So add it in the *ngIfThen statement?那么将它添加到 *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>

I think you can simplify with ng-switch :我认为您可以使用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;
}

With ng-switch your template looks much cleaner and easier to read.使用ng-switch您的模板看起来更清晰、更易于阅读。 You can show/hide the ng-container through a boolean variable that gets toggled once the user selects one hand type.您可以通过布尔变量显示/隐藏ng-container ,一旦用户选择一种型,该变量就会切换。

I do not know your logic, but you have to re-enable the ng-container , if the user has the possibility to choose an hand again.我不知道你的逻辑,但你必须重新启用ng-container ,如果用户有可能再次选择一手牌

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM