angular - 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'
});
});
}
}
}
你能给我解释一下为什么吗?这里有什么神奇的吗?
谢谢!
解决方案
如果类型已更改,您似乎想滚动到元素的位置。在这种情况下,以下代码将以更角度的方式执行此操作。
Directive({
selector: '[appCustomName]'
})
export class CustomNameDirective {
@Input() set type(_type: string) {
window.scroll({
top: this.elementRef.offsetTop,
behavior: 'smooth'
})
}
constructor(private elementRef: ElementRef) { }
}
推荐阅读
- excel - 我想将引用单元格地址的变量传递给 Excel 电子表格中的求和公式
- optimization - 如何进一步优化代码以克服 TLE 错误?
- html - 从 URL 根之上的相对路径提供 CSS?
- mongodb - mongodb中是否有任何查询可以从对象数组中查找特定对象
- javascript - 我怎样才能优化这个jquery
- c++ - 可以使用 schannel 与 nginx 等网络服务器建立 ssl 连接
- sql - SQL:选择其他包含空值的列
- python - 有没有办法将多个 jupyter 笔记本合并为一个?
- javascript - Outlook-addin 不适用于从 GitHub 下载的离线 office.js
- javascript - pdfmake中存在特殊字符时文件名错误