【问题标题】:ng-bootstrap: accordion reinitializes componentng-bootstrap:手风琴重新初始化组件
【发布时间】:2017-03-19 23:40:13
【问题描述】:

我在 ng-bootstrap 中使用 ngb-accordion。切换标题会导致其子组件重新初始化。例如,切换标题会导致下拉菜单重置。看起来这是因为<div class="card-block"></div>在面板隐藏时被删除了。

即使组件“隐藏”在手风琴中,我如何维护它们的状态?

模板文件:

<ngb-accordion activeIds="side-bar-accordion-1" (panelChange)="beforeChange($event)">

  <div [class.hide-card-block]="status">
  <ngb-panel id="side-bar-accordion-1" class="foo">
    <template ngbPanelTitle>
        <div class="title">Axes</div>
    </template>
    <template ngbPanelContent>
        <!--This is the component whose state I want to maintain:-->
        <side-bar-axes></side-bar-axes>
    </template>
  </ngb-panel>
  </div>

  <ngb-panel id="side-bar-accordion-2">
    <template ngbPanelTitle>
      <div class="title">Fancy</div>
    </template>
    <template ngbPanelContent>
      blah blah
    </template>
  </ngb-panel>

  <ngb-panel id="side-bar-accordion-3">
    <template ngbPanelTitle>
        <div class="title">Settings</div>
    </template>
    <template ngbPanelContent>
      blah blah
    </template>
  </ngb-panel>

</ngb-accordion>

组件 TypeScript 文件:

import { Component, ViewChildren, ViewEncapsulation } from '@angular/core';
import { NgbPanelChangeEvent } from '@ng-bootstrap/ng-bootstrap';

import { FieldChooseFiltersComponent } from '../field-choose-filters/field-choose-filters.component';

@Component({
  moduleId: module.id,
    selector: 'side-bar',
    templateUrl: 'side-bar.component.html',
    styleUrls: ['side-bar.component.css'],
  encapsulation: ViewEncapsulation.None
})

export class SideBarComponent {
  hideNum: number = 1;
  status: boolean = false;

  toggleStatus() {
    this.status = !this.status;
  }
  public beforeChange($event: NgbPanelChangeEvent) {

    if ($event.panelId === '1' && $event.nextState === false) {
      $event.preventDefault();
    }

    if ($event.panelId === '2' && $event.nextState === false) {
      $event.preventDefault();
    }

    if ($event.panelId === '3' && $event.nextState === false) {
      $event.preventDefault();
    }
  };
}

【问题讨论】:

    标签: twitter-bootstrap angular ng-bootstrap


    【解决方案1】:

    https://ng-bootstrap.github.io/#/components/accordion 的当前实现假定只有活动(可见)面板外壳保留在 DOM 中。这是一个有意识的设计决定,因为保留不可见的面板意味着:

    • 即使从未显示,他们的内容也会被初始化
    • Angular 必须对不可见且不会增加最终用户体验的部分运行更改检测。

    所以,目前一切都按设计进行。如果您想在面板打开/关闭时保留状态,一种选择是将相关状态移动到父组件之一。

    如果社区有足够的兴趣,我们可能会添加一个选项,以便在面板关闭时不销毁面板的内容。

    【讨论】:

    • 是的,它现在的工作方式对大多数项目都有意义。但是,如果有一个选项可以防止破坏面板内容,那就太棒了!谢谢
    • 我们需要不破坏面板内容。请提供不破坏面板内容的选项
    • 目前这个答案不应该被接受,因为它误导了其他开发者,因为这个选项已经可用了!
    【解决方案2】:

    NgbAccordion 具有输入选项destroyOnHide。它必须是假的。查看文档here。 示例:&lt;ngb-accordion [destroyOnHide]="false"&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多