Home > Back-end >  Angular - making a Toggle to replace divs
Angular - making a Toggle to replace divs

Time:04-21

I am trying to make a toggle switch to replace a section on a page with another div of content

<!-- Toggle - Changes page layout on Click-->
<div >
  <p  >option 1</p>
  <label  >
    <input type="checkbox" (click)="toggle()" >
    <span  ></span>
  </label>
  <p  >option 2</p>
</div>


<div >


<!-- Page Content -->

</div>

<!-- next button -->
<div >
  <button type="button"  (click)="nextpage1()">Next</button>
</div>
</div>


<!-- page content 2 -->
<ng-container *ngIf="show">
<div class ="page2" >
  

  <!-- Page Content -->
  <div class= "content text-center">
      
  <!-- next button - Link to either Growth or Mindset page, dependant on which is toggled -->
  <div >
    <button type="button"  (click)="nextpage2()">Next</button>
  </div>
</div>
</ng-container>

and my typescript

 toggle(){
    this.show = !this.show;

    if(this.show)
      this.switch = "Hide";
    else
      this.switch = "Show";
  }

The page 2 content shows and hides fine but I want to replace/hide the page 1 content on a toggle switch and vice versa, but unsure on how to do this

CodePudding user response:

To create a toggle, you just have to use templates when the conditions are met.

I'll give you a generic example with a more "clean" syntax :


<ng-container *ngIf="show; then showTpl; else hideTpl">
</ng-container>

<button (click)="show = !show">
  Toggle view
</button>

<ng-template #showTpl>
  This part is shown when show variable is set to true
</ng-template>

<ng-template #hideTpl>
  This part is shown when show variable is set to false
</ng-template>

  • Related