Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-bootstrap collapse: How to apply animations?

I'm using Collapse: https://ng-bootstrap.github.io/#/components/collapse

However, it does not animate; even not on the demo site. How should I implement this??

like image 999
Boland Avatar asked Oct 19 '16 23:10

Boland


1 Answers

Here's a good way to do it, I think, and it works both for revealing and collapsing: (though it doesn't really need ng-bootstrap anymore)

template.html:

<button (click)="isCollapsed = !isCollapsed">Toggle</button>
<p [@smoothCollapse]="isCollapsed?'initial':'final'">
    your data here
</p>

.

component.ts:

import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'app-my-component',
  templateUrl: './template.html',
  styleUrls: ['./style.scss'],
  animations: [
    trigger('smoothCollapse', [
      state('initial', style({
        height:'0',
        overflow:'hidden',
        opacity:'0'
      })),
      state('final', style({
        overflow:'hidden',
        opacity:'1'
      })),
      transition('initial=>final', animate('750ms')),
      transition('final=>initial', animate('750ms'))
    ]),
  ]
})
export class MyComponent ...

Details:

  • initial height:0 allows to start from nothing
  • not specifying a final height let the element stop growing when it's all displayed
  • overflow:hidden everywhere so your element doesn't run on other elements
  • opacity from 0 to 1 makes it nicer (in my opinion)
  • An important thing which took me some time to realize is to NOT put [ngbCollapse]="isCollapsed" in the <p> otherwise it breaks all the animation. And we don't need it since we set the height to 0

Hope it helps, I spent a day on it :P

like image 120
Loki Faër Avatar answered Sep 20 '22 17:09

Loki Faër