adrigm
11/19/2018 - 4:14 AM

Collapse Directive

Collapse Directive

import { Directive, Input, ElementRef, OnChanges } from '@angular/core';

@Directive({
  selector: '[appCollapse]'
})
export class CollapseDirective implements OnChanges {
  @Input() appCollapse: boolean;
  height = 0;
  init = false;

  constructor(private el: ElementRef) {}

  ngOnChanges() {
    this.el.nativeElement.classList.add('st-collapse');

    if (!this.init) {
      this.height = this.el.nativeElement.offsetHeight;
      this.init = true;
    }

    if (this.appCollapse) {
      this.el.nativeElement.classList.add('show');
      this.el.nativeElement.style.maxHeight = this.height + 'px';

      setTimeout(() => {
        this.el.nativeElement.style.maxHeight = null;
      }, 300);
    } else {
      this.height = this.el.nativeElement.offsetHeight;
      this.el.nativeElement.style.maxHeight = this.height + 'px';
      setTimeout(() => {
        this.el.nativeElement.classList.remove('show');
        this.el.nativeElement.style.maxHeight = '0px';
      }, 0);
    }
  }
}
.st-collapse {
  display: block;
  overflow: hidden;
  opacity: 0.3;
  transition: max-height .3s ease-in-out, opacity .3s;

  &.show {
    opacity: 1;
    transition: opacity 0.3s ease;
    transition: max-height .3s  ease-in-out, opacity .3s;
  }
}