Home > Mobile >  How to multiple ng-bootstrap collapse component in single page?
How to multiple ng-bootstrap collapse component in single page?

Time:10-12

I want to use this collapse component in my page multiple times , but after clicking on any one of them all of them collapse, it want only the one clicked to be collapsed

CodePudding user response:

In this SO, I try to explain how works ngb-collapse

If you has "several" ngb-collapse you need "several" variables. If you use the approach of use template reference variable

  <!--see that the template reference variable are 
      "collapse1", "collapse2" and "collapse3" -->
  <button type="button" (click)="collapse1.toggle()">Toggle</button>
  <div #collapse1="ngbCollapse" [ngbCollapse]>..</div>

  <button type="button" (click)="collapse2.toggle()">Toggle</button>
  <div #collapse2="ngbCollapse" [ngbCollapse]>..</div>

  <button type="button" (click)="collapse3.toggle()">Toggle</button>
  <div #collapse3="ngbCollapse" [ngbCollapse]>..</div>

If you has under a *ngFor, you needn't take account, Angular give a diferent "scope" to the elements under the *ngFor

  <!--under a *ngFor Angular get the property "scope"-->
  <ng-container *ngFor="let i of [0,1,2]">
    <button type="button" (click)="collapse.toggle()">Toggle</button>
    <div #collapse="ngbCollapse" [ngbCollapse]>..</div>
  </ng-container>

If you take the aproach of use a variable use an array (or different variables)

  collapsed:boolean[]=[] //declare an array in .ts

  <button type="button" (click)="collapse[0]=!collapse[0]">Toggle</button>
  <div #collapse1="ngbCollapse" [ngbCollapse]="collapse[0]">..</div>

  <button type="button" (click)="collapse[1]=!collapse[1]">Toggle</button>
  <div [ngbCollapse]="collapse[1]">..</div>

  <button type="button" (click)="collapse[2]=!collapse[2]">Toggle</button>
  <div [ngbCollapse]="collapse[2]">..</div>

Or using ngFor

  <ng-container *ngFor="let item of [1,2,3];i=index">
      <button type="button" (click)="collapse[i]=!collapse[i]">Toggle</button>
      <div [ngbCollapse]="collapse[i]">..</div>
   </ng-container>

NOTE I update removing unnecessary template reference variable for the case of use a variable

CodePudding user response:

I guess you need to use a separate "collapse" variable in the template and "isCollapsed" in the ts file. That will solve your problem.

  • Related