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
ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet.
Setting up wildcard routeslink To add this functionality to your application, you set up a wildcard route. The Angular router selects this route any time the requested URL doesn't match any router paths. To set up a wildcard route, add the following code to your routes definition.
Angular Router supports multiple outlets in the same application. A component has one associated primary route and can have auxiliary routes. Auxiliary routes enable developers to navigate multiple routes at the same time.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With