resize.directive.ts 712 Bytes
Newer Older
liujiaxin's avatar
liujiaxin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
import {Directive, ElementRef, EventEmitter, Output} from '@angular/core';
import {ResizeSensor} from 'css-element-queries';
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';

@Directive({
  selector: '[appResize]'
})
export class ResizeDirective {
  @Output()
  resize = new EventEmitter();
  debounce = new Subject();

  constructor(private el: ElementRef) {
    this.debounce
      .pipe(debounceTime(100))
      .subscribe(rect => {
        this.resize.emit(rect);
      });

    const sensor = new ResizeSensor(this.el.nativeElement, (event) => {
      const {clientWidth, clientHeight} = this.el.nativeElement;
      this.debounce.next({clientWidth, clientHeight});
    });
  }

}