首页 > 解决方案 > Angular 8 - 为什么 window.scroll 不能处理生命周期钩子 ngOnchanges()?

问题描述

我使用 Angular 8 创建了一个指令,如下所示:

Directive({
  selector: '[appCustomName]'
})
export class CustomNameDirective implements OnChanges {
  @Input() type: string;

  constructor(
    private elementRef: ElementRef,
    private renderer: Renderer2
  ) {}

  ngOnChanges(changes: SimpleChanges): void {
    const element = this.elementRef.nativeElement;

    if (changes.type && changes.type.currentValue) {
      window.scroll({
        top: element.offsetTop,
        behavior: 'smooth'
      });
    }
  }
}

上面的代码不适用于 window.scroll 定位,但是当我 setTimeout() 时它工作正常。

Directive({
  selector: '[appCustomName]'
})
export class CustomNameDirective implements OnChanges {
  @Input() type: string;

  constructor(
    private elementRef: ElementRef,
    private renderer: Renderer2
  ) {}

  ngOnChanges(changes: SimpleChanges): void {
    const element = this.elementRef.nativeElement;

    if (changes.type && changes.type.currentValue) {
      setTimeout(() => {
        window.scroll({
          top: element.offsetTop,
          behavior: 'smooth'
        });
      });
    }
  }
}

你能给我解释一下为什么吗?这里有什么神奇的吗?

谢谢!

标签: angular

解决方案


如果类型已更改,您似乎想滚动到元素的位置。在这种情况下,以下代码将以更角度的方式执行此操作。

Directive({
    selector: '[appCustomName]'
})
export class CustomNameDirective {
    @Input() set type(_type: string) {
        window.scroll({
            top: this.elementRef.offsetTop,
            behavior: 'smooth'
        })
    }

    constructor(private elementRef: ElementRef) { }
}

推荐阅读