Search code examples
angulartypescriptng-switch

Use ngSwitch to switch between components in Angular 11 a href?


I have to child components and I want to be able to switch between two sub components but it not working. I have no idea how to implement it here.

This is my example code

HTML

<h3 class="first">Choose View</h3>
<a options="A">A</a>
<a options="B">B</a>
<p>Selected Type: <span style="font-weight: bold">{{selectedType}}</span></p>

<!-- Switching Mechanism -->

<div [ngSwitch]="selectedType">
  <li *ngSwitchCase="'A'"> <app-component-a></app-component-a>
  <li *ngSwitchCase="'B'">  <app-component-b></app-component-b>
  <li *ngSwitchDefault><app-component-b></app-component-b>
</div>

STACKBLITZ


Solution

  • Your problems are:

    • Missing closing tags
    • li inside of a div
    • Not sure what options="A" is supposed to do, you need to set the selectedType variable
    <h3 class="first">Choose View</h3>
    <a (click)="selectedType='A'">A</a><br />
    <a (click)="selectedType='B'">B</a>
    <p>Selected Type: <span style="font-weight: bold">{{selectedType}}</span></p>
    
    <!-- Switching Mechanism -->
    
    <ul [ngSwitch]="selectedType">
      <li *ngSwitchCase="'A'"> <app-component-a></app-component-a></li>
      <li *ngSwitchCase="'B'">  <app-component-b></app-component-b></li>
      <li *ngSwitchDefault><app-component-b></app-component-b></li>
    </ul>
    

    Updated Stackblitz

    Instead of using ngSwitch you could more simply do this:

    <app-component-a *ngIf="selectedType == 'A'"></app-component-a>
    <app-component-b *ngIf="selectedType != 'A'"></app-component-b>