Search code examples
angulartypescriptfrontendangular-ng-if

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.

I want to go for the option to hide the whole ng-container. Is there a way I can hide the ng-container after clicking on one of the buttons? So add it in the *ngIfThen statement?

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

Solution

  • I think you can simplify with 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. You can show/hide the ng-container through a boolean variable that gets toggled once the user selects one hand type.

    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.