Angular 5:用于导航到相同路线但参数不同的路线动画 [英] Angular 5: Route animations for navigating to the same route, but different parameters
问题描述
在我的 Angular 5 应用程序中,用户可以导航到使用相同路线但具有不同参数的路线.例如,他们可以从 /page/1
导航到 /page/2
.
我希望此导航触发路由动画,但它没有.如何让路由器动画在这两条路线之间发生?
(我已经明白,与大多数路由更改不同,此导航不会销毁并创建新的 PageComponent
.解决方案是否更改此行为对我来说并不重要.)>
这是一个老问题,但如果您仍在搜索,那就是了.将此代码添加到您的 app.Component.ts 文件中.
import { Router, NavigationEnd } from '@angular/router';构造函数(私有_Router:路由器){}ngOnInit() {this._Router.routeReuseStrategy.shouldReuseRoute = function(){返回假;};this._Router.events.subscribe((evt) => {if (evt instanceof NavigationEnd) {this._Router.navigated = false;window.scrollTo(0, 0);}});}
通过使用此代码,无论您添加到路由的参数是什么,如果您单击同一路由,页面都会刷新.
希望能帮到你.
更新
随着 angular 6 与核心更新一起发布,您不再需要这些代码,只需将以下参数添加到路由导入中即可.
onSameUrlNavigation: '重新加载'
此选项值默认设置为 'ignore'
.
示例
@NgModule({进口:[RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload'})],出口:[路由器模块]})
保持最新状态并快乐编码.
In my Angular 5 application, the user may navigate to a route which uses the same route, but with different parameters. For example, they may navigate from /page/1
to /page/2
.
I want this navigation to trigger the routing animation, but it doesn't. How can I cause a router animation to happen between these two routes?
(I already understand that unlike most route changes, this navigation does not destroy and create a new PageComponent
. It doesn't matter to me whether or not the solution changes this behavior.)
Here's a minimal app that reproduces my issue.
This is an old question but that's it if you're still searching. Add this code to your app.Component.ts file.
import { Router, NavigationEnd } from '@angular/router';
constructor(private _Router: Router) { }
ngOnInit() {
this._Router.routeReuseStrategy.shouldReuseRoute = function(){
return false;
};
this._Router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
this._Router.navigated = false;
window.scrollTo(0, 0);
}
});
}
By using this code the page is going to refresh if you clicked on the same route no matter what is the parameter you added to the route.
I hope that helps.
Update
As angular 6 is released with core updates you don't need this punch of code anymore just add the following parameter to your routs import.
onSameUrlNavigation: 'reload'
This option value set to 'ignore'
by default.
Example
@NgModule({
imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload'})],
exports: [RouterModule]
})
Stay up to date and happy coding.
这篇关于Angular 5:用于导航到相同路线但参数不同的路线动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!