Reputation: 83
Here is the example, I have some routes defined in AppComponent
:
@RouteConfig([
{path:'/', name: 'Index', component: IndexComponent, useAsDefault: true},
{path:'/:id/...', name: 'User', component: UserComponent},
{path:'/plan', name: 'Plan', component: PlanComponent},
{path:'/foo', name: 'Foo', component: FooComponent}
]}
and in UserComponent
I have another route defined like this :
@RouteConfig([
{path:'/info', name: 'UserInfo', component: UserInfoComponent, useAsDefault: true},
{path:'/order', name: 'UserOrder', component: UserOrderComponent},
{path:'/detail', name: 'UserDetail', component: UserDetailComponent}
]}
There are 2 separate navigations defined in both AppComponent
and UserComponent
:
//AppComponent:
<a [routerLink]="['User']">User</a>
<a [routerLink]="['Plan']">Plan</a>
<a [routerLink]="['Foo']">Foo</a>
--------------------------------------------
//UserComponent:
<a [routerLink]="['UserInfo']">User Info</a>
<a [routerLink]="['UserOrder']">User Order</a>
<a [routerLink]="['UserDetail']">User Detail</a>
The behavior I expect is:
When user click on these navigations, a modal will comes up and ask user if he confirm to save before leaving this route. if yes, save the user's change automatically.
Since it seems that there is no way to get these changes in UserComponent
, I want to put the logic into these child components (UserInfoComponent
, UserOrderComponent
and UserDetailComponent
). So is there any way I can trigger a callback when user leave the current route inside the child component? if not, is there any alternative way to achieve that? Thanks
Upvotes: 7
Views: 10194
Reputation: 16540
Router already comes with lifecycle hooks , CanDeactivate Interface
The hook to allow/deny navigating away is routerCanDeactivate(nextInstruction, prevInstruction) { ... }
. It will stop the navigation if you return false from this function.
Example With Plunker: (in the plunker, route 2 will never allow navigating away. You cannot go back to route 1)
@Component({
selector:'route-2',
template:'route 2 template'
})
class SecondRoute{
routerCanDeactivate(){
return false; // false stops navigation, true continue navigation
}
}
Upvotes: 7