Angular hide and showing multiple divs

Viewed 2736

Farely new to angular, and I've tried looking online for examples of what I'm trying to achieve, but all of the examples don't seem to be helping me

I have 5 tabs, each tab represents a body of info. I want it to originally show the first boxes info, but when you click on the other boxes, it will replace it with the other boxes info

So basically, a hide and show. Only showing the info of the box I clicked. Heres a layout of what I mean HTML:

<div class="boxes">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>

<div class="box1-content">Lorem ipsum 1</div>
<div class="box2-content">Lorem ipsum 1</div>
<div class="box3-content">Lorem ipsum 1</div>
<div class="box4-content">Lorem ipsum 1</div>
<div class="box5-content">Lorem ipsum 1</div>

CSS:

 .boxes {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
    grid-gap: 10px;
    padding: 10px;
    }

    .box {
     height: 100px;
     background: red;
    }

https://codepen.io/anon/pen/gZZYpR

2 Answers

change your .html like this

<div class="boxes">
<div class="box" (click)="tabToggle(1)">box1</div>
<div class="box" (click)="tabToggle(2)">box2</div>
<div class="box" (click)="tabToggle(3)">box3</div>
<div class="box" (click)="tabToggle(4)">box4</div>
<div class="box" (click)="tabToggle(5)">box5</div>
</div>

<div *ngIf="showTab == 1" class="box1-content">Lorem ipsum 1</div>
<div *ngIf="showTab == 2" class="box2-content">Lorem ipsum 2</div>
<div *ngIf="showTab == 3" class="box3-content">Lorem ipsum 3</div>
<div *ngIf="showTab == 4" class="box4-content">Lorem ipsum 4</div>
<div *ngIf="showTab == 5" class="box5-content">Lorem ipsum 5</div>

add this line on your .ts file's under component.

  showTab = 1;
  tabToggle(index){
    this.showTab =index;
  }

hope I can help some!

First I would set the content boxes to display: none; (using css) and then attach a click function to your .box divs which might look like this:

<div class="boxes">
<div class="box" (click)="showThis = 'show1'"></div>
<div class="box" (click)="showThis = 'show2'"></div>
<div class="box" (click)="showThis = 'show3'"></div>
<div class="box" (click)="showThis = 'show4'"></div>
<div class="box" (click)="showThis = 'show5'"></div>
</div>

<div class="box1-content" *ngIf="showThis == 'show1'">Lorem ipsum 1</div>
<div class="box2-content" *ngIf="showThis == 'show2'">Lorem ipsum 1</div>
<div class="box3-content" *ngIf="showThis == 'show3'">Lorem ipsum 1</div>
<div class="box4-content" *ngIf="showThis == 'show4'">Lorem ipsum 1</div>
<div class="box5-content" *ngIf="showThis == 'show5'">Lorem ipsum 1</div>

Also, my first choice would be to use a library like Material or even bootstrap so you don't have to worry about all this logic/styling. But either way, hope this helps!

Related