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定位,但当我设置Timeout((时,它就可以正常工作了。

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'
});
});
}
}
}

你能为我解释一下原因吗?这里有什么神奇的东西吗?

谢谢!

如果类型发生变化,您似乎希望滚动到元素的位置。在这种情况下,下面的代码将以一种更有角度的方式进行操作。

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

最新更新