Angular 4+ bootstrap NgbAccordion如何扩展/折叠全部

时间:2018-03-23 16:39:20

标签: angular typescript ng-bootstrap

我一直在和ng-bootstrap一起玩角,我对以下内容感到难过:

我的页面上有这个NgbAccordion:

<ngb-accordion #acc="ngbAccordion">
    <ngb-panel *ngFor="let container of answer.resultObj.containers.containers" title="{{container.metadata.title}}">
      <ng-template ngbPanelContent>
        <app-containers [container]="container"></app-containers>
      </ng-template>
    </ngb-panel>
  </ngb-accordion>

这导致点亮的ngb-panel全部崩溃。这正是我想要的,我可以通过点击它来切换app容器对象的扩展。

我还想要一个按钮来展开所有ngb-panel 。我似乎无法让它发挥作用。我找到了一个基于Angularjs(&lt; 2)的好例子,但这不起作用,似乎一次出现的[isOpen]选项不再存在了?!

我的角色成分:

import {Component, Input} from '@angular/core';
import {Answer} from '../model/answer';
@Component({
  selector: 'app-answer',
  templateUrl: './answer.component.html',
  styleUrls: ['./answer.component.css'],
  providers: []
})
export class AnswerComponent {
  @Input() answer: Answer;

  constructor() {
  }
}

任何帮助将不胜感激......

2 个答案:

答案 0 :(得分:11)

您可以使用手风琴上的activeIds输入

https://ng-bootstrap.github.io/#/components/accordion/api

基本上,为每个面板分配一个唯一的ID

<ngb-panel *ngFor="let container ...; let i= index" title="Panel{{i}}" id="panel-{{i}}"

并在您的组件中声明一个活动ID列表(=必须打开的面板的ID)

activeIds: string[] = [];

然后在要打开/关闭面板时修改该列表

this.activeIds = [];//All panels closed
this.activeIds = ['panel-1', 'panel-2']; //panels 1 and 2 are open

并将此变量绑定到手风琴的activeIds输入

<ngb-accordion #acc="ngbAccordion" [activeIds]="activeIds"

最后,添加按钮

<button (click)="activeIds=[]" >close all</button>
<button (click)="openAll()" >open all</button>

openAll()
{
    this.activeIds = [/* add all panel ids here */];
}

我创建了一个stackblitz来说明这个

https://stackblitz.com/edit/angular-nzzwnc?file=app%2Fapp.component.ts

答案 1 :(得分:1)

=这是一个解决方案,允许您一次只打开一个手风琴。 您可以与(panelChange)一起使用,捕获ngb的更改,如下所示:

html:

   <ngb-accordion #acc="ngbAccordion"  [activeIds]="activeId"  (panelChange)="toggleAccordian($event)">
    <ngb-panel *ngFor="let option of options;" title="{{option}}">
        <ng-template ngbPanelContent>
                    <ul class="nav nav-tabs">
                      <!--some code-->
                    </ul>
        </ng-template>
    </ngb-panel>
</ngb-accordion>

ts:

activeId: string = "";

toggleAccordian(event) {
    // If it is already open you will close it and if it is closed open it
    this.activeId = this.activeId == event.panelId ? "" : event.panelId;
}