【问题标题】:Scroll to Top of Document After Param Change in Angular 4?Angular 4中的参数更改后滚动到文档顶部?
【发布时间】:2018-04-01 04:23:34
【问题描述】:

我已经编写了 app.component.ts 文件,以便在每次页面状态更改后使用 renderer.setElementProperty 滚动到我的应用顶部。

我还有一个 example.com/product/xx 页面,其中“xx”代表不同的参数。我编写了一个 route.param.subscribe 来监听参数变化并根据新参数获取页面内容。

我的问题主要出在手机(浏览器视图)或内容较长的页面上。

我的代码监听参数变化,更新内容,但滚动到页面顶部,虽然我的 app.component.ts 文件用我的标准路线变更。

我尝试了 window.scrollTo(0, 0) 和其他几个基于 JavaScript 的窗口操作均无济于事。

是否有人在路由参数订阅中成功编写了滚动回顶部功能?

编码如下所示

this.route.params
    .subscribe(item => {
        this.item = item; // successfully retrieves param content
        window.scrollTo(0, 0); // does not scroll to top
        this.renderer.setElementProperty(document.body, "scrollTop", 0);
        // also does not work
    });
});

在 Angular 4 (4.4.x) 应用程序中成功侦听来自路由的参数后,有什么想法可以注入“滚动到顶部”功能?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    试试这样:

    component.ts

    import { Inject } from '@angular/core';
    import { DOCUMENT } from '@angular/platform-browser';
    
    export class Component {
        constructor( @Inject(DOCUMENT) private document: Document) { }
    
        this.route.params.subscribe(item => {
            this.item = item; // successfully retrieves param content   
            this.document.body.scrollTop = 0;
        })
    }
    

    【讨论】:

    • 感谢您的建议,因为我没有尝试导入 DOCUMENT。不幸的是,这似乎也不起作用。然后我读到需要在 app.module.ts 文件的导入数组中最后导入路由模块并最后移动它。它仍然没有工作。会继续努力。
    【解决方案2】:

    @Arg0n 对帖子 How to reload the current route with the angular 2 router 的出色回复中找到答案。

    我的全部目的是在每次更改参数后滚动到产品页面的顶部。 就目前而言,参数更改不会刷新 URL 的状态,因为路由本身并未更改。我已将 Arg0 的响应中的代码添加到上面的代码中(用于 routes.param 监听):

    // reset item object based on params id change
    this.route.params
        .subscribe(params => {
            this.id = params['id'];
            this.router.routeReuseStrategy.shouldReuseRoute = function() {
                return false;
            }
    
            // get item object
            this.productService.getItem(this.id)
                .subscribe(item => {
                    this.item = item;
                });
    
            });
        }
    

    现在,当加载新项目(参数更改)时,页面会模仿非 SPA 应用程序并滚动到页面顶部(没有非 SPA 应用程序的闪烁)。

    【讨论】:

      猜你喜欢
      • 2019-11-01
      • 1970-01-01
      • 2021-09-30
      • 2015-08-04
      • 2021-12-15
      • 2020-10-01
      • 1970-01-01
      • 2019-05-15
      相关资源
      最近更新 更多