const routers: Router = [
{
path: 'abc',
data: {
headerTitle: 'Đây là title của ABC'
}
},
{
path: ':id/:name/detail',
component: DatasourceDetailComponent,
data: {
headerTitle: '//:name//',
breadcrumb: [
{
label: 'Home',
url: '/'
},
{
label: 'Datasources',
url: '/datasource-management'
},
{
label: '//:name//',
}
]
}
}
]
<span *ngIf="headerTitle" class="page-title">
{{headerTitle}}
</span>
$page-title-height: 60px;
$header-padding: 24px;
.page-title {
height: $page-title-height;
line-height: $page-title-height !important;
font-size: 24px;
color: #172B4D;
padding: 0 $header-padding;
font-family: "FVHCircularXX-Regular";
}
// https://stackoverflow.com/questions/50877410/angular-6-get-current-activatedRoute-and-its-data
import { ChangeDetectorRef } from '@angular/core';
import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router, NavigationEnd } from "@angular/router";
import { filter, map } from "rxjs/operators";
@Component({
selector: 'page-header-title',
templateUrl: './page-header-title.component.html',
styleUrls: ['./page-header-title.component.scss']
})
export class PageHeaderTitleComponent implements OnInit {
headerTitle = '';
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private cdr: ChangeDetectorRef
) {
}
ngOnInit() {
// if reload current page
this.buildHeaderTitle(this.activatedRoute);
// if router navigate
this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe(() => {
this.buildHeaderTitle(this.activatedRoute);
});
}
/*
ideal:
buildHeaderTitle: get params val from url
getheaderTitle build headerTitle from snapshot.data and replace dynamic value
*/
buildHeaderTitle(route: ActivatedRoute) {
/* Resolve the problem is that I was trying to access the ActivatedRoute from a Component which is outside the <router-outlet>
https://stackblitz.com/edit/angular-param-service?file=app%2Fapp.component.ts
*/
let params = route.snapshot.params
params = { ...route.snapshot.queryParams, ...params }
if (route.children) {
for (let r of route.children) {
params = { ...this.buildHeaderTitle(r), ...params };
}
}
this.headerTitle = this.getheaderTitle(route, params);
return params;
}
getheaderTitle(route, params): string | null {
let child = route.firstChild;
let sliceChar = '//';
let headerTitle = '';
while (child) {
if (child.firstChild) {
child = child.firstChild;
} else if (child.snapshot.data && child.snapshot.data['headerTitle']) {
const breadCrumbLabelSplitArray = child.snapshot.data['headerTitle'].split(sliceChar);
const breadCrumbWithLabelMappingVal = breadCrumbLabelSplitArray.map(label => {
if (label.charAt(0) === ':') {
const labelMappingParam = params[label.slice(1, label.length)];
label = labelMappingParam ? labelMappingParam : label;
}
return label;
});
headerTitle = breadCrumbWithLabelMappingVal.join('');
child = null;
} else {
child = null;
}
}
return headerTitle;
}
}