Shakti
Shakti

Reputation: 271

How to change title of a page using angular(angular 2 or 4) route?

I want to change the title of the page whenever I click or browse the link from the URL bar. How to change that using Angular route? I am using angular version 4 and angular cli.

Upvotes: 26

Views: 18715

Answers (4)

Federico Baù
Federico Baù

Reputation: 7675

Angular version 14 (2022)

Just add a title key in the routes const. For instance

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

// Components
import {ViewHomeComponent} from "./components/home.component";


const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full'},
  { path: 'home', component: ViewHomeComponent, title: 'Home' }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export default class ModuleHomeRouting {}

That will set automatically the title to 'Home'!

Upvotes: 0

Shubham Verma
Shubham Verma

Reputation: 9933

You can to use @angular/plateform-browser to use the setTitle():

import { Title } from '@angular/platform-browser';

@Component({
  selector: 'your-component',
})

export class YourComponent implements onInit {
  constructor(private title: Title) {}

 ngOnInit() {
     this.title.setTitle('Title for this component');
 }

}

Upvotes: 25

Rinshan Kolayil
Rinshan Kolayil

Reputation: 1139

I have tried with following way with few lines of code, hope it will help you.

You can pass any name in the data object of routes variable (app-routing.module.ts) as follows

const routes: Routes = [
  {
    path: '', 
    component: Component,
    data: {
      page_title: 'Title of your page'
    }

  }
]

Then fetch the value of page_title in the data object of the routes into the app.component.ts and set as title.

import { Router, RoutesRecognized } from '@angular/router';
import { Title } from '@angular/platform-browser';
export class AppComponent {
  page_title = '';
  constructor(private titleService: Title, private route: Router) {
    route.events.subscribe(event => {
      if (event instanceof RoutesRecognized) {
        let current_route = event.state.root.firstChild;
        this.page_title = current_route?.data.page_title;
        if (this.page_title == undefined) {
          alert('Please set page title for the routing')
        }
        else {
          titleService.setTitle(this.page_title);
        }

      }
    });
  }
}

You can also try to declare the service then copy the codes in the constructor to a function inside the service and do the necessary imports, After call the function of service inside constructor of app.component.ts which will help in future projects.

Upvotes: 0

Hootan Alavizadeh
Hootan Alavizadeh

Reputation: 411

you have to pass "title" as data to your route

const routes: Routes = [{
  path: 'calendar',
  component: CalendarComponent,
  children: [
    { path: '', redirectTo: 'new', pathMatch: 'full' },
    { path: 'all', component: CalendarListComponent, data: { title: 'My Calendar' } },
    { path: 'new', component: CalendarEventComponent, data: { title: 'New Calendar Entry' } },
    { path: ':id', component: CalendarEventComponent, data: { title: 'Calendar Entry' } }
  ]
}];

Then do this imports in your Component:

import { Title } from '@angular/platform-browser';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

Once imported, we can inject them both:

@Component({
  selector: 'app-root',
  templateUrl: `
    <div>
      Hello world!
    </div>
  `
})
export class AppComponent {
  constructor( private router: Router,
               private activatedRoute: ActivatedRoute,
               private titleService: Title) {}
}

To update a page title statically, we can simply call setTitle like so:

ngOnInit() {
     this.router.events
        .filter((event) => event instanceof NavigationEnd)
        .map(() => this.activatedRoute)
        .map((route) => {
            while (route.firstChild) route = route.firstChild;
            return route;
        })
        .filter((route) => route.outlet === 'primary')
        .mergeMap((route) => route.data)
        .subscribe((event) => {
            let title = 'Default Title Here'
            if(event['title']) {
                title = event['title'];
            }
            this.titleService.setTitle(title);
        });
}

Upvotes: 14

Related Questions