angular - 使用 typescript (javascript)触发 ng-bootstrap Accordion 组件?

标签 angular twitter-bootstrap typescript ng-bootstrap

我正在使用 ng-bootstrap framework在我的 Angular 4 项目中。

我的应用程序中的多个位置都有“ Accordion ”组件,在某些情况下,我需要在 typescript 中触发 Accordion 打开状态。

来自accordion component API documentation我找到了以下方法,但据我所知,它仅在 html 文件中调用时有效(尝试从构造函数调用)。

//Programmatically toggle a panel with a given id.
toggle(panelId: string) => void

是否也可以在 typescript 中触发? 如果有人对此有经验,我将非常感激。否则我需要构建自己的自定义 Accordion 。

最佳答案

为此,您必须使用带有 NgbAccordion 组件的强类型 ViewChild

您可以对 ng-boostrap 的任何组件和任何子组件的任何公共(public)方法执行相同的操作。

要遵循的步骤:

1/将#someIdentifier 添加到 html 端的组件标签中。

2/使用@ViewChild('someIdentifier') 引用您的component.ts

3/通过 ComponentType StrongCast 你的属性。

4/从您的子组件中享受任何公共(public)方法。

下面的例子:

import {Component, ViewChild} from '@angular/core';
import {NgbAccordion} from '@ng-bootstrap/ng-bootstrap';
@Component({
  selector: 'ngbd-accordion-toggle',
  templateUrl: './accordion-toggle.html'
})
export class NgbdAccordionToggle {
  @ViewChild('acc') accordionComponent: NgbAccordion;

  // Method call on click.
  toggle(id:string): void {
  //Here you have access to AccordionComponent as discribe on documentation.    
    this.accordionComponent.toggle(id);
  }
}

HTML 端:

<ngb-accordion #acc="ngbAccordion">
// [...]
</ngb-accordion>

实例:https://stackblitz.com/edit/angular-szhpdw?file=app%2Faccordion-toggle.ts

关于angular - 使用 typescript (javascript)触发 ng-bootstrap Accordion 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49613227/

相关文章:

Angular 2 JSON 解析不起作用

magento - 是否可以使用 Twitter Bootstrap 创建 Magento 网站?

javascript - 枚举成员如何在 TypeScript 中使用别名?

android - 在 chrome 开发工具上模拟低分辨率设备

Angular --prod build 从编译的 CSS 中剥离 SVG 属性

css - 防止 ng-cli 将 css 关联到组件

javascript - Angular 中如何从 json 中获取数据分页

javascript - Bootstrap Popover 中的 Share This 按钮不可点击

twitter-bootstrap - x 在 Bootstrap 4 中可编辑?

Angular AOT编译错误 "cannot determine module for class Component''