Angular2 ng2-bootstrap collapse add transition/animation

ShadowFoOrm picture ShadowFoOrm · Aug 22, 2016 · Viewed 12.9k times · Source

I m using this https://valor-software.com/ng2-bootstrap/#/collapse and i would like to add an animation/transition on height 0 - auto but we all know that you can't add transition on height auto. I would like to add a slideToggle efect with a duration on it. tried to look for a solution for over 3 days...

is there a known solution for this?

Answer

yurzui picture yurzui · Sep 11, 2016

Animation is coming soon in ng2-bootstrap. You just need to wait a bit.

1) Today you can leverage as workaround the following:

@Component({
  selector: 'my-app',
  template: `
       <button type="button" class="btn btn-primary"
           (click)="isCollapsed = !isCollapsed">Toggle collapse
      </button>
      <div (collapsed)="setHeight(el, 0)"
           (expanded)="setHeight(el, 0);setHeight(el, el.scrollHeight)"
           [collapse]="isCollapsed"
           class="card card-block card-header block"  #el>
        <div class="well well-lg">Some content</div>
      </div>
  `,
  styles: [`
    .block {
      display: block !important;
      overflow: hidden !important;
      -webkit-transition: height .5s;
      transition: height .5s;
    }
  `]
})
export class App {
  isCollapsed: boolean = true;

  constructor(private renderer: Renderer) { }

  setHeight(el, height) {
    this.renderer.setElementStyle(el, 'height', height + 'px');
  }
}

See also a working Plunker Example

2) Without the CollapseDirective directive you can do it like this

@Component({
  selector: 'my-app',
  template: `
    <button type="button" class="btn btn-primary"
      (click)="height = height ? 0 : el.scrollHeight">Toggle collapse
    </button>

    <div       
      class="card card-block card-header block" [style.height]="height + 'px'" #el> 
      <div class="well well-lg">Some content</div>
    </div>
  `,
  styles: [`
    .block {
      overflow: hidden;
      -webkit-transition: height .5s;
      transition: height .5s;
    }
  `]
})
export class App {
  height = 0;
}

Plunker Example