I have a simple route with 1 parameter:
{
path: 'item/:id',
component: ItemComponent,
data: {title: 'Item detail'}
}
I'm setting page title using data title property in main AppComponent:
export class AppComponent implements OnInit {
title: string;
ngOnInit() {
this.router.events
.. parse it
.subscribe((event) => {
this.title = event['title'];
});
}
}
Then I'm just displaying it in AppComponent template:
<h1>{{ title }}</h1>
The problem is if I want to have dynamic title like "Item detail #name(:id)"
. Is there any way how can I add e.g. route param (:id) or variable into data title property? Something like
{
path: 'item/:id',
component: ItemComponent,
data: {title: 'Item detail #' + :id }
}
To extract the parameter, you need to make the dynamic parameter in the route path so that you can extract the value of the parameter by parameter name.
There are various ways by which we can pass data from one component to another. Angular 7.2. 0 introduced a new way to pass data using State Object while navigating between routed components.
Like I said in the comments, you could keep the data.title
param as a blueprint and replace the dynamic part from within the component.
Route declaration:
{
path: 'item/:id',
component: ItemComponent,
data: { title: 'Item detail [id]' }
}
In data.title
, I wrote [id]
to make replacement easier but feel free to use whatever symbols you'd like to delimitate the string to replace.
Then, in the component:
export class AppComponent {
title: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
const titlePattern = this.route.snapshot.data['title'];
const id = this.route.snapshot.params['id'];
this.title = titlePattern.replace('[id]', id);
}
}
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