Search code examples
angularionic-frameworkweb-componentangular-componentsblockly

Choose whether to show one component or another with ionic and angular framework


I am developing an app with ionic and angular. In one specific page I added a component into the ion-content, however now I want to choose to display another one when I click a button. I have been looking for an option but it has been imposible for me to find how to do it. This is my actual code:

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="end">
      <ion-button (click)="changeComponent()" color="primary">
        <ion-icon name="copy-outline"></ion-icon>
      </ion-button>
    </ion-buttons>    
  </ion-toolbar>
</ion-header>

<ion-content>
 <app-blockly></app-blockly>
</ion-content>

What I want to do is to add in the ion-content another component called app-dual-blockly that has to be seen only when I click the changeComponent button and hide the actual app-blocky.

Thank you very much.


Solution

  • define your boolean properties to show components or not:

    public showComponentA = false;
    public showComponentB = false;
    

    When clicking the button, toggle the action

    changeComponent() {
        this.showComponentA = !this.showComponentA;
    }
    
    changeComponentB() {...}
    

    In this case, you can easily work with *NgIf

    <ion-content>
     <app-blockly *ngIf="showComponentA"></app-blockly>
     <another-component *ngIf="showComponentB"></another-component>
    </ion-content>
    

    If things grow, you can either choose a Angular Router or use a switchStatement. For only two Components, this should do the trick.

    https://angular.io/api/common/NgSwitch