1

My project is in angular 2. I make tabs collapse, I want my collapse hidden if button click again but made from data dynamic or looping:

My html Code :

  <button (click)="item = 1" class="navbar-toggler navbar-toggler-right" type="button" class="btn mr-3">tab 1</button>
  <button (click)="item = 2" class="navbar-toggler navbar-toggler-right" type="button" class="btn">tab 2</button>

  <div class="collapse" [class.show]="item === 1">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos cumque voluptate dolorem tenetur nesciunt!
  </div>
  <div class="collapse" [class.show]="item === 2">
      Tempora iure porro incidunt laboriosam earum nesciunt repellendus culpa, iste doloribus provident aut, ipsam,
      consectetur quam!
  </div>
dan1st
  • 12,568
  • 8
  • 34
  • 67
Edi
  • 11
  • 2
  • Check the answers here; https://stackoverflow.com/questions/45467248/animation-on-angular-4-doesnt-seem-to-have-transition-effect – Ralpharoo Nov 27 '19 at 03:43
  • see https://codecraft.tv/courses/angular/built-in-directives/ngif-and-ngswitch/ – dasunse Nov 27 '19 at 03:56

3 Answers3

1

If it is just showing and hiding data try ngIf

<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>Content to render when condition is true.</ng-template>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>

If you need to add or remove a class try ngClass

[ngClass]="{'show': item == 1}"
Vinaayakh
  • 512
  • 1
  • 6
  • 17
1

working Demo

You can use [class] attribute in angular to achieve this

Html

 <button (click)="item = 1" [class] ="item===1? 'navbar-toggler navbar-toggler-right btn mr-3 btn btn-info' : 'navbar-toggler navbar-toggler-right btn mr-3'" type="button" >tab 1</button>
  <button (click)="item = 2" [class] ="item===2? 'navbar-toggler navbar-toggler-right btn mr-3 btn btn-info' : 'navbar-toggler navbar-toggler-right btn mr-3'" type="button" >tab 2</button>

  <div [class]="item == 1? 'collapse': ''">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos cumque voluptate dolorem tenetur nesciunt!
  </div>
  <div  [class]="item == 2? 'collapse': ''">
    Tempora iure porro incidunt laboriosam earum nesciunt repellendus culpa, iste doloribus provident aut, ipsam,
    consectetur quam!
  </div> 

in .ts

item = 1;

hope this will helps ...!

dasunse
  • 2,839
  • 1
  • 14
  • 32
DeC
  • 2,226
  • 22
  • 42
0

You can achieve it just by replacing [class.show] with *ngIf

Working Demo

  <div class="collapse" *ngIf="item == 1">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos cumque voluptate dolorem tenetur nesciunt!
  </div>
  <div class="collapse" *ngIf="item == 2">
    Tempora iure porro incidunt laboriosam earum nesciunt repellendus culpa, iste doloribus provident aut, ipsam,
    consectetur quam!
  </div>

Note: if you want to show the first tab by default, set item=1 in .ts file

Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79