The official documentation tells to use title
property of Route
to set page title. https://angular.io/guide/router#setting-the-page-title
Each page in your application should have a unique title so that they can be identified in the browser history. The Router sets the document's title using the title property from the Route config.
But I get this error:
Type '{ path: string; title: string; component: typeof SecondComponent; }' is not assignable to type 'Route'. Object literal may only specify known properties, and 'title' does not exist in type 'Route'.
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { SingleComponent } from './single/single.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FirstComponent } from './first/first.component';
import { SecondComponent } from './second/second.component';
import { ChildAComponent } from './child-a/child-a.component';
import { ChildBComponent } from './child-b/child-b.component';
const routes: Routes = [
{ path: 'first', component: FirstComponent, children: [
{ path: 'child-a', component: ChildAComponent },
{ path: 'child-b', component: ChildBComponent },
]},
{ path: 'second', title: 'Second page title', component: SecondComponent }, // here an error
{ path: 'single', component: SingleComponent },
{ path: '', redirectTo: '/first', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
CodePudding user response:
Title is not recognized property in Angular 13. See the API reference here. But it is in Angular 14. So your code will work on Angular 14 but not in 13
CodePudding user response:
You're trying to use the Angular 14's route API, which is only in beta actually :)
Under version 14, if you want to set page title, you must use data
property and set a property "title", such as :
{
path: 'tralala',
component: TralalaComponent,
data: {
title: 'My Title'
}
}
Then, in your page component (TralalaComponent), inject the Angular's TitleService and the ActivatedRoute in order to retrieve the data
object, get your title and set it.
export class TralalaComponent implement OnInit {
constructor(
private readonly route: ActivatedRoute,
private readonly titleService: Title
) {}
ngOnInit(): void {
this.titleService.setTitle(this.route.snapshot.data['title'])
}
}