指令是否可以避免布局垃圾?

时间:2017-09-13 10:58:13

标签: angular

我想知道Renderer2是否有某种机制来避免布局垃圾。如果屏幕上没有更多空间,让我们有一个示例指令重定位工具提示:

import { Directive, ElementRef, HostListener, AfterViewInit, Renderer2 } from '@angular/core';


@Directive({
  selector: '[fooDirective]',
  exportAs: 'fooDirective'
})
export class FooDirective implements AfterViewInit {
  constructor(private el: ElementRef, private renderer: Renderer2) {
  }

  public ngAfterViewInit(): void {
    this.onResize();
  }

  @HostListener('window:resize')
  public onResize(): void {
    this.el.nativeElement.style.left = null;
    this.el.nativeElement.style.top = null;

    const bounds = this.el.nativeElement.getBoundingClientRect();
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;

    if (windowWidth < bounds.right) {
      this.renderer.setStyle(this.el.nativeElement, 'left', `calc(100% - ${bounds.right - windowWidth}px)`);
    }

    if (windowHeight < bounds.bottom) {
      this.renderer.setStyle(this.el.nativeElement, 'top', `calc(0px - ${bounds.bottom - windowHeight}px)`);
    }
  }
}

onResize中有两个条件可以重叠,例如https://github.com/wilsonpage/fastdom,但我想知道是否有必要?也许angular2自己处理这个?

1 个答案:

答案 0 :(得分:0)

不,渲染器会立即执行您的任务from the sources

class DefaultDomRenderer2 implements Renderer2 {
      setStyle(el: any, style: string, value: any, flags: RendererStyleFlags2): void {
        if (flags & RendererStyleFlags2.DashCase) {
          el.style.setProperty(
              style, value, !!(flags & RendererStyleFlags2.Important) ? 'important' : '');
        } else {
          el.style[style] = value;
        }
      }