简体   繁体   English

如何以编程方式折叠/展开 Bootstrap 折叠?

[英]How to Collapse / Expand a Bootstrap Collapse programmatically?

<button data-toggle="collapse" data-target="#demo">Collapsible</button>

<div id="demo" class="collapse">
Lorem ipsum dolor text....
</div>

For example imagine this is in app.component.html in the Angular project.例如,假设这是在 Angular 项目的app.component.html中。

There is a variable called showMenu in app.component.ts app.component.ts 中有一个叫做 showMenu 的变量

let showMenu: boolean;

I want the above div to collapse when showMenu is false and expand when showMenu is true.我希望上面的 div 在 showMenu 为 false 时折叠并在 showMenu 为 true 时展开。

Is this possible?这可能吗?

Use ngClass like shown below to achieve the desired effect. 如下所示使用ngClass来达到所需的效果。

<div id="demo" class="collapse" [ngClass]="{'show': showMenu}">
    Lorem ipsum dolor text....
</div>

The collapse is actually adding/removing the ' show ' class internally to hide/show the element. 折叠实际上是在内部添加/删除“ show ”类以隐藏/显示元素。 You can do the same using angular like above. 您可以使用上述的角度进行相同的操作。

I believe your best bet is to swap the showMenu variable with a function that you can call when you change the value. 我相信最好的选择是将showMenu变量与一个更改值时可以调用的函数交换。 I realize that may not be ideal so your other option is to implement ngOnChanges() like so: 我意识到这可能并不理想,因此您的另一个选择是像这样实现ngOnChanges()

ngOnChanges(changes) {
  if (this.showMenu) {
    $('#demo').collapse('show');
  } else {
    $('#demo').collapse('hide');
  }
}

Remember to import and add ngOnChanges to your class too. 记住也要导入ngOnChanges并将其添加到您的类中。

Looking for the same answer I got to this:寻找相同的答案我得到了这个:

ngOnChanges(changes) {
   $('#demo').collapse('toggle');
}

Enjoy!享受!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM