** If I want to use other module instead of app.module
use
ng g m demo\demo --flat --routing
to generate demo module and demo-routing module
in xxx.routing.module.ts
const routes: Routes = [
{
path: 'myCarts',
component: MyCartsComponent,
data:{
breadcrumb: 'My Carts',
},
canDeactivate: [CanDeactivateGuard],
children: [
{
path: 'cart/:id',
component: CartSummaryComponent,
data:{
breadcrumb: 'id',
},
children: [
{
path: 'product/:sku',
component: ProductDetailComponent,
},
{
path: 'upload',
component: UploadToCartComponent
}
]
},
{
path: 'cartSearch/:searchKeyWord',
component: CartSearchComponent
},
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class MyCartsRoutingModule { }
use
<div>
<router-outlet></router-outlet>
</div>
in HTML.
For example,
in myAccount html, write
<div>
<router-outlet></router-outlet>
</div>
and in myAccount component,
this.router.navigate(['users'], {
relativeTo: this.activatedRouter.parent,
queryParams: {
category: category
}
});
the page will be redirected to /myAccount/users?category=category and use HTML of users
or
if I am in /myAccount/xxx,
in xxx component,
this.router.navigate(['users'], {
relativeTo: this.activatedRouter.parent,
queryParams: {
category: category
},
skipLocationChange: true // hide query parameter
});
the page will be redirected to /myAccount/users and use HTML of users
/*go to parent page*/
this.router.navigate(["../"], {relativeTo: this.activatedRoute})
1. create a file
import { Injectable } from '@angular/core';
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
2. write canDeactivate method in component
// return true then can leave this component/page, false then can not leave this component/page
canDeactivate(): Observable<boolean> | boolean {
if (this.isSaveSuccessful) {
return true;
}
if (!this.isAccommodationWelfareDetailsSame()) {
this.modalService.showModal();
return this.modalService.stayOnThePage;
} else {
this.modalService.hideModal();
return true;
}
}