how to change page title in angular2 router





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







54















I am trying to change the page title from the router, can this be done?



import {RouteConfig} from 'angular2/router';
@RouteConfig([
{path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {}









share|improve this question




















  • 8





    Use the Title service. I know there's an answer over there but can't find it.

    – Eric Martinez
    Jan 5 '16 at 2:22











  • New link to Title service: angular.io/docs/ts/latest/api/platform-browser/index/…

    – weltschmerz
    Oct 7 '16 at 23:41






  • 1





    See also stackoverflow.com/questions/38644314/…

    – Günter Zöchbauer
    Mar 3 '17 at 8:06













  • I had same problem and the best answer I found was confirmed answer for this question: stackoverflow.com/questions/38644314/…

    – moshtaba morsali
    Feb 14 '18 at 9:36











  • New link to Title service angular.io/guide/set-document-title

    – Alf Moh
    Aug 13 '18 at 14:10


















54















I am trying to change the page title from the router, can this be done?



import {RouteConfig} from 'angular2/router';
@RouteConfig([
{path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {}









share|improve this question




















  • 8





    Use the Title service. I know there's an answer over there but can't find it.

    – Eric Martinez
    Jan 5 '16 at 2:22











  • New link to Title service: angular.io/docs/ts/latest/api/platform-browser/index/…

    – weltschmerz
    Oct 7 '16 at 23:41






  • 1





    See also stackoverflow.com/questions/38644314/…

    – Günter Zöchbauer
    Mar 3 '17 at 8:06













  • I had same problem and the best answer I found was confirmed answer for this question: stackoverflow.com/questions/38644314/…

    – moshtaba morsali
    Feb 14 '18 at 9:36











  • New link to Title service angular.io/guide/set-document-title

    – Alf Moh
    Aug 13 '18 at 14:10














54












54








54


14






I am trying to change the page title from the router, can this be done?



import {RouteConfig} from 'angular2/router';
@RouteConfig([
{path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {}









share|improve this question
















I am trying to change the page title from the router, can this be done?



import {RouteConfig} from 'angular2/router';
@RouteConfig([
{path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {}






typescript angular angular2-routing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 28 '16 at 5:31









drewmoore

19.3k1566100




19.3k1566100










asked Jan 5 '16 at 1:26









B HullB Hull

1,12351623




1,12351623








  • 8





    Use the Title service. I know there's an answer over there but can't find it.

    – Eric Martinez
    Jan 5 '16 at 2:22











  • New link to Title service: angular.io/docs/ts/latest/api/platform-browser/index/…

    – weltschmerz
    Oct 7 '16 at 23:41






  • 1





    See also stackoverflow.com/questions/38644314/…

    – Günter Zöchbauer
    Mar 3 '17 at 8:06













  • I had same problem and the best answer I found was confirmed answer for this question: stackoverflow.com/questions/38644314/…

    – moshtaba morsali
    Feb 14 '18 at 9:36











  • New link to Title service angular.io/guide/set-document-title

    – Alf Moh
    Aug 13 '18 at 14:10














  • 8





    Use the Title service. I know there's an answer over there but can't find it.

    – Eric Martinez
    Jan 5 '16 at 2:22











  • New link to Title service: angular.io/docs/ts/latest/api/platform-browser/index/…

    – weltschmerz
    Oct 7 '16 at 23:41






  • 1





    See also stackoverflow.com/questions/38644314/…

    – Günter Zöchbauer
    Mar 3 '17 at 8:06













  • I had same problem and the best answer I found was confirmed answer for this question: stackoverflow.com/questions/38644314/…

    – moshtaba morsali
    Feb 14 '18 at 9:36











  • New link to Title service angular.io/guide/set-document-title

    – Alf Moh
    Aug 13 '18 at 14:10








8




8





Use the Title service. I know there's an answer over there but can't find it.

– Eric Martinez
Jan 5 '16 at 2:22





Use the Title service. I know there's an answer over there but can't find it.

– Eric Martinez
Jan 5 '16 at 2:22













New link to Title service: angular.io/docs/ts/latest/api/platform-browser/index/…

– weltschmerz
Oct 7 '16 at 23:41





New link to Title service: angular.io/docs/ts/latest/api/platform-browser/index/…

– weltschmerz
Oct 7 '16 at 23:41




1




1





See also stackoverflow.com/questions/38644314/…

– Günter Zöchbauer
Mar 3 '17 at 8:06







See also stackoverflow.com/questions/38644314/…

– Günter Zöchbauer
Mar 3 '17 at 8:06















I had same problem and the best answer I found was confirmed answer for this question: stackoverflow.com/questions/38644314/…

– moshtaba morsali
Feb 14 '18 at 9:36





I had same problem and the best answer I found was confirmed answer for this question: stackoverflow.com/questions/38644314/…

– moshtaba morsali
Feb 14 '18 at 9:36













New link to Title service angular.io/guide/set-document-title

– Alf Moh
Aug 13 '18 at 14:10





New link to Title service angular.io/guide/set-document-title

– Alf Moh
Aug 13 '18 at 14:10












13 Answers
13






active

oldest

votes


















54














The Title service @EricMartinez points out has a setTitle() method - that's all you need to set the title.



In terms of doing it automatically on route changes, as of now there's no built-in way of doing this other than subscribing to Router and calling setTitle() in your callback:



import {RouteConfig} from 'angular2/router';
import {Title} from 'angular2/platform/browser';

@RouteConfig([
{path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {
constructor(router:Router, title:Title) {
router.events.subscribe((event)=>{ //fires on every URL change
title.setTitle(getTitleFor(router.url));
});
}
}


That said, I emphasize as of now because the router is still under heavy development, and I expect (or at least hope) that we'll be able to do this via RouteConfig in the final release.



EDIT:



As of the release of Angular 2 (2.0.0), a few things have changed:




  • The docs for the Title service are now here: https://angular.io/docs/ts/latest/api/platform-browser/index/Title-class.html

  • The service is imported from '@angular/platform-browser'






share|improve this answer





















  • 3





    Also router.subscribe is now router.events.subscribe in Angular2

    – Romesh
    Dec 7 '16 at 10:41








  • 1





    getTitleFor(url) this method returns what ? i.e value of name in router config ?

    – Kaleem Ullah
    Feb 2 '17 at 9:24











  • If I'm reading the docs correctly, getTitleFor() is no longer a thing.

    – Brendan
    Feb 17 '17 at 18:23






  • 1





    I found this answer to be a bit more detailed

    – adamdport
    Jul 5 '17 at 19:53



















15














Here's my approach which works fine, especially for nested routes:



I use a recursive helper method to grab the deepest available title after a route has changed:



@Component({
selector: 'app',
template: `
<h1>{{title | async}}</h1>
<router-outlet></router-outlet>
`
})
export class AppComponent {
constructor(private router: Router) {
this.title = this.router.events
.filter((event) => event instanceof NavigationEnd)
.map(() => this.getDeepestTitle(this.router.routerState.snapshot.root));
}

title: Observable<string>;

private getDeepestTitle(routeSnapshot: ActivatedRouteSnapshot) {
var title = routeSnapshot.data ? routeSnapshot.data['title'] : '';
if (routeSnapshot.firstChild) {
title = this.getDeepestTitle(routeSnapshot.firstChild) || title;
}
return title;
}
}


This is assuming, that you have assigned page titles within the data property of your routes, like this:



{
path: 'example',
component: ExampleComponent,
data: {
title: 'Some Page'
}
}





share|improve this answer


























  • I was looking for the data property at router.routeSnapshot.root.data, but it appears that it can be nested based on how the route is setup. This answer worked for me.

    – The Muffin Man
    Feb 16 '17 at 20:57











  • I had to add this.title = this.getDeepestTitle(this.activatedRoute.snapshot.root); for this to work on the first visit.

    – Mel
    Jan 23 '18 at 15:54



















13














For Angular 4+:



If you want to use route custom data to define page title for every route path, the following approach will work for the nested routes and with angular version 4+:



You can pass page title in your route definition:



  {path: 'home', component: DashboardComponent, data: {title: 'Home Pag'}},
{path: 'about', component: AboutUsComponent, data: {title: 'About Us Page'}},
{path: 'contact', component: ContactUsComponent, data: {title: 'Contact Us Pag'}},


Now, most important in your upper level component (ie AppComponent), you can globally catch the route custom data on every route change and update the page title:



import {Title} from "@angular/platform-browser";
export class AppComponent implements OnInit {

constructor(
private activatedRoute: ActivatedRoute,
private router: Router,
private titleService: Title
) { }

ngOnInit() {
this.router
.events
.filter(event => event instanceof NavigationEnd)
.map(() => {
let child = this.activatedRoute.firstChild;
while (child) {
if (child.firstChild) {
child = child.firstChild;
} else if (child.snapshot.data && child.snapshot.data['title']) {
return child.snapshot.data['title'];
} else {
return null;
}
}
return null;
}).subscribe( (title: any) => {
this.titleService.setTitle(title);
});
}
}


The above code is tested against angular verion 4+.






share|improve this answer



















  • 1





    Great! Just some more additions. Be sure to add import { BrowserModule, Title } from '@angular/platform-browser'; and set the providers: [Title] in the Module, and also have to add import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; in the Component. Otherwise you can get some errors.

    – BogdanD
    Apr 13 '18 at 8:43





















8














Its really very easy to do this, you can follow therse steps to see the immediate effects:



we provide the Title service in bootstrap:



import { NgModule } from '@angular/core';
import { BrowserModule, Title } from '@angular/platform-browser';

import { AppComponent } from './app.component';

@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent
],
providers: [
Title
],
bootstrap: [ AppComponent ]
})
export class AppModule { }


Then import this service in the component you want:



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

@Component({
selector: 'my-app',
template:
`<p>
Select a title to set on the current HTML document:
</p>

<ul>
<li><a (click)="setTitle( 'Good morning!' )">Good morning</a>.</li>
<li><a (click)="setTitle( 'Good afternoon!' )">Good afternoon</a>.</li>
<li><a (click)="setTitle( 'Good evening!' )">Good evening</a>.</li>
</ul>
`
})
export class AppComponent {
public constructor(private titleService: Title ) { }

public setTitle( newTitle: string) {
this.titleService.setTitle( newTitle );
}
}


now click on those links to see the title changing.



you can also use ng2-meta for changing page title and description as well,you can refer to this link:



https://github.com/vinaygopinath/ng2-meta






share|improve this answer


























  • yeah superb answer, using this we can change title and description as well , No need to use Title service of angular2 extra in your code, thanks for answer.

    – Pardeep Jain
    Jan 31 '17 at 7:49











  • @PardeepJain Will this solution work even though my app takes 4 seconds to load? I've used ng2-meta and that doesn't work because of my app loading time. (I've tried everything to reduce the loading time)

    – AngularM
    Feb 8 '17 at 11:20








  • 2





    What if user enter the page url and press enter OR Refresh the page, will it work. I can see you copy the same code from document :) angular.io/docs/ts/latest/cookbook/set-document-title.html

    – Ali Adravi
    Apr 14 '17 at 0:05





















5














Angular 2 provides a Title Service see Shailesh answer is just copy of that code.



I our app.module.ts



import { BrowserModule, Title } from '@angular/platform-browser';
........
providers: [..., Title],
bootstrap: [AppComponent]


Now move to our app.component.ts



import { Title }     from '@angular/platform-browser';
......
export class AppComponent {

public constructor(private titleService: Title ) { }

public setTitle( newTitle: string) {
this.titleService.setTitle( newTitle );
}
}


Put the title tag on your component html and it will read and set for you.



If you want to know how to set it dynamically and further detail see this article






share|improve this answer































    2














    This is what I went with:



    constructor(private router: Router, private title: Title) { }

    ngOnInit() {
    this.router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
    this.title.setTitle(this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).join(' - '));
    }
    });
    }

    recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
    var titleParts = <string>;
    if (snapshot) {
    if (snapshot.firstChild) {
    titleParts = titleParts.concat(this.recursivelyGenerateTitle(snapshot.firstChild));
    }

    if (snapshot.data['title']) {
    titleParts.push(snapshot.data['title']);
    }
    }

    return titleParts;
    }





    share|improve this answer
























    • Fantastic, only tweak I made was to ensure a title on the HTML document and tweaked this line of your code (note the reverse()), this.title.setTitle(this.title.getTitle().split(' - ')[0] + ' - ' + this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).reverse().join(' - '));.

      – Tim Harker
      Apr 28 '17 at 1:40








    • 1





      Or alternatively, you could use unshift() instead of push() and then reverse().

      – Tim Harker
      Apr 28 '17 at 1:49



















    1














    import {Title} from "@angular/platform-browser"; 
    @Component({
    selector: 'app',
    templateUrl: './app.component.html',
    providers : [Title]
    })

    export class AppComponent implements {
    constructor( private title: Title) {
    this.title.setTitle('page title changed');
    }
    }





    share|improve this answer































      1














      Here's the simplest way to change the Title of the page, when pages/views are navigated (Tested as of Angular @2.3.1). Simply apply the following solution to all the views you have and you should be good to go:



      Example Code in About Us page/view:



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

      export class AboutUsComponent implements OnInit {

      constructor(private _titleService: Title) {
      }

      ngOnInit() {
      //Set page Title when this view is initialized
      this._titleService.setTitle('About Us');
      }

      }


      Example Code in Contact Us page/view:



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

      export class ContactusComponent implements OnInit {

      constructor(private _titleService: Title) {
      }

      ngOnInit() {
      //Set page Title
      this._titleService.setTitle('Contact Us');
      }

      }





      share|improve this answer































        1














        In the below example:



        -We added object of data: { title: 'NAME' } to any routing object.



        -We set a basic name ("CTM") for uploading time (when clicking F5 for Refreash..): <title>CTM</title>.



        -We added "TitleService" class.



        -we handle Routher events by filtering them from app.component.ts.



        index.html:



        <!DOCTYPE html>
        <html>
        <head>
        <base href="/">
        <title>CTM</title>
        </head>


        ...



        app.module.ts:



        import { NgModule, enableProdMode } from '@angular/core';
        import { BrowserModule } from '@angular/platform-browser';
        import { TitleService } from './shared/title.service';
        ...


        @NgModule({
        imports: [
        BrowserModule,
        ..
        ],
        declarations: [
        AppComponent,
        ...
        ],
        providers: [
        TitleService,
        ...
        ],
        bootstrap: [AppComponent],
        })
        export class AppModule { }

        enableProdMode();


        title.service.ts:



        import { Injectable } from '@angular/core';
        import { Title } from '@angular/platform-browser';
        import { ActivatedRouteSnapshot } from '@angular/router';


        @Injectable()
        export class TitleService extends Title {

        constructor() {
        super();
        }


        private recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
        var titleParts = <string>;
        if (snapshot) {
        if (snapshot.firstChild) {
        titleParts = this.recursivelyGenerateTitle(snapshot.firstChild);
        }

        if (snapshot.data['title']) {
        titleParts.push(snapshot.data['title']);
        }
        }

        return titleParts;
        }

        public CTMGenerateTitle(snapshot: ActivatedRouteSnapshot) {
        this.setTitle("CTM | " + this.recursivelyGenerateTitle(snapshot).join(' - '));
        }

        }


        app-routing.module.ts:



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

        import { MainComponent } from './components/main.component';

        import { Router, CanActivate } from '@angular/router';
        import { AuthGuard } from './shared/auth/auth-guard.service';
        import { AuthService } from './shared/auth/auth.service';


        export const routes: Routes = [
        { path: 'dashboard', component: MainComponent, canActivate: [AuthGuard], data: { title: 'Main' } },
        ];

        @NgModule({
        imports: [
        RouterModule.forRoot(routes, { useHash: true }) // .../#/crisis-center/
        ],
        exports: [RouterModule],
        providers: [
        ..
        ]
        })

        export class AppRoutingModule { }

        export const componentsOfAppRoutingModule = [MainComponent];


        app.component.ts:



        import { Component } from '@angular/core';
        import { Router, NavigationEnd, ActivatedRouteSnapshot } from '@angular/router';
        import { TitleService } from './shared/title.service';

        @Component({
        selector: 'ctm-app',
        template: `
        <!--<a [routerLink]="['/dashboard']">Dashboard</a>
        <a [routerLink]="['/login']">Login</a>
        <a [routerLink]="['/']">Rooting</a>-->
        <router-outlet></router-outlet>
        `
        })
        export class AppComponent {

        constructor(private router: Router, private titleService: TitleService) {

        this.router.events.filter((event) => event instanceof NavigationEnd).subscribe((event) => {
        console.log("AppComponent.constructor: Setting HTML document's Title");
        this.titleService.CTMGenerateTitle(this.router.routerState.snapshot.root);
        });

        }


        }





        share|improve this answer

































          1














          Angular 6+
          I have modify the old code using new Pipe() and its working fine.



          import { Title } from '@angular/platform-browser';
          import { filter, map, mergeMap } from 'rxjs/operators';


          ...



          constructor(
          private router: Router,
          public activatedRoute: ActivatedRoute,
          public titleService: Title,
          ) {
          this.setTitle();
          }


          ....



          setTitle() {
          this.router.events.pipe(
          filter((event) => event instanceof NavigationEnd),
          map(() => this.activatedRoute),
          map((route: any) => {
          while (route.firstChild) route = route.firstChild;
          return route;
          }),
          filter((route) => route.outlet === 'primary'),
          mergeMap((route: any) => route.data)).subscribe((event) => {
          this.titleService.setTitle(event['title']);
          console.log('Page Title', event['title']);
          })
          }





          share|improve this answer

































            0














            I can also recommend @ngx-meta/core plugin plugin that I've just released, in the case if you're looking for a method to set page title and meta tags dynamically.






            share|improve this answer

































              0














              Angular 6+



              if route configured as follow :-



              Routes = [
              { path: 'dashboard',
              component: DashboardComponent,
              data: {title: 'Dashboard'}
              }]


              **Then in component constructor title can be set as follow :- **



               constructor( private _titleService: Title, public activatedRoute: ActivatedRoute) {
              activatedRoute.data.pipe(map(data => data.title)).subscribe(x => this._titleService.setTitle(x));
              }





              share|improve this answer































                0














                Working fine in Angular 6 and 6+ with Pipe and map method instead of using filter



                Step1: routing setup



                {path: 'dashboard', component: DashboardComponent, data: {title: 'My Dashboard'}},
                {path: 'aboutUs', component: AboutUsComponent, data: {title: 'About Us'}},
                {path: 'contactUs', component: ContactUsComponent, data: {title: 'Contact Us Page'}},


                step2: in your app.module.ts import module



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


                then in provider add providers: [title]



                Step 3
                In your main component import



                import { Title } from "@angular/platform-browser";
                import { RouterModule, ActivatedRoute, Router, NavigationEnd } from "@angular/router";
                import { filter, map } from 'rxjs/operators';

                constructor(private titleService: Title, private router: Router, private activatedRoute: ActivatedRoute) {

                }

                ngOnInit() {

                this.router.events.pipe(map(() => {
                let child = this.activatedRoute.firstChild;
                while (child) {
                if (child.firstChild) {
                child = child.firstChild;
                } else if (child.snapshot.data && child.snapshot.data['title']) {
                return child.snapshot.data['title'];
                } else {
                return null;
                }
                }
                return null;
                })).subscribe(title => {
                this.titleService.setTitle(title);
                });

                }





                share|improve this answer


























                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34602806%2fhow-to-change-page-title-in-angular2-router%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  13 Answers
                  13






                  active

                  oldest

                  votes








                  13 Answers
                  13






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  54














                  The Title service @EricMartinez points out has a setTitle() method - that's all you need to set the title.



                  In terms of doing it automatically on route changes, as of now there's no built-in way of doing this other than subscribing to Router and calling setTitle() in your callback:



                  import {RouteConfig} from 'angular2/router';
                  import {Title} from 'angular2/platform/browser';

                  @RouteConfig([
                  {path: '/home', component: HomeCmp, name: 'HomeCmp' }
                  ])
                  class MyApp {
                  constructor(router:Router, title:Title) {
                  router.events.subscribe((event)=>{ //fires on every URL change
                  title.setTitle(getTitleFor(router.url));
                  });
                  }
                  }


                  That said, I emphasize as of now because the router is still under heavy development, and I expect (or at least hope) that we'll be able to do this via RouteConfig in the final release.



                  EDIT:



                  As of the release of Angular 2 (2.0.0), a few things have changed:




                  • The docs for the Title service are now here: https://angular.io/docs/ts/latest/api/platform-browser/index/Title-class.html

                  • The service is imported from '@angular/platform-browser'






                  share|improve this answer





















                  • 3





                    Also router.subscribe is now router.events.subscribe in Angular2

                    – Romesh
                    Dec 7 '16 at 10:41








                  • 1





                    getTitleFor(url) this method returns what ? i.e value of name in router config ?

                    – Kaleem Ullah
                    Feb 2 '17 at 9:24











                  • If I'm reading the docs correctly, getTitleFor() is no longer a thing.

                    – Brendan
                    Feb 17 '17 at 18:23






                  • 1





                    I found this answer to be a bit more detailed

                    – adamdport
                    Jul 5 '17 at 19:53
















                  54














                  The Title service @EricMartinez points out has a setTitle() method - that's all you need to set the title.



                  In terms of doing it automatically on route changes, as of now there's no built-in way of doing this other than subscribing to Router and calling setTitle() in your callback:



                  import {RouteConfig} from 'angular2/router';
                  import {Title} from 'angular2/platform/browser';

                  @RouteConfig([
                  {path: '/home', component: HomeCmp, name: 'HomeCmp' }
                  ])
                  class MyApp {
                  constructor(router:Router, title:Title) {
                  router.events.subscribe((event)=>{ //fires on every URL change
                  title.setTitle(getTitleFor(router.url));
                  });
                  }
                  }


                  That said, I emphasize as of now because the router is still under heavy development, and I expect (or at least hope) that we'll be able to do this via RouteConfig in the final release.



                  EDIT:



                  As of the release of Angular 2 (2.0.0), a few things have changed:




                  • The docs for the Title service are now here: https://angular.io/docs/ts/latest/api/platform-browser/index/Title-class.html

                  • The service is imported from '@angular/platform-browser'






                  share|improve this answer





















                  • 3





                    Also router.subscribe is now router.events.subscribe in Angular2

                    – Romesh
                    Dec 7 '16 at 10:41








                  • 1





                    getTitleFor(url) this method returns what ? i.e value of name in router config ?

                    – Kaleem Ullah
                    Feb 2 '17 at 9:24











                  • If I'm reading the docs correctly, getTitleFor() is no longer a thing.

                    – Brendan
                    Feb 17 '17 at 18:23






                  • 1





                    I found this answer to be a bit more detailed

                    – adamdport
                    Jul 5 '17 at 19:53














                  54












                  54








                  54







                  The Title service @EricMartinez points out has a setTitle() method - that's all you need to set the title.



                  In terms of doing it automatically on route changes, as of now there's no built-in way of doing this other than subscribing to Router and calling setTitle() in your callback:



                  import {RouteConfig} from 'angular2/router';
                  import {Title} from 'angular2/platform/browser';

                  @RouteConfig([
                  {path: '/home', component: HomeCmp, name: 'HomeCmp' }
                  ])
                  class MyApp {
                  constructor(router:Router, title:Title) {
                  router.events.subscribe((event)=>{ //fires on every URL change
                  title.setTitle(getTitleFor(router.url));
                  });
                  }
                  }


                  That said, I emphasize as of now because the router is still under heavy development, and I expect (or at least hope) that we'll be able to do this via RouteConfig in the final release.



                  EDIT:



                  As of the release of Angular 2 (2.0.0), a few things have changed:




                  • The docs for the Title service are now here: https://angular.io/docs/ts/latest/api/platform-browser/index/Title-class.html

                  • The service is imported from '@angular/platform-browser'






                  share|improve this answer















                  The Title service @EricMartinez points out has a setTitle() method - that's all you need to set the title.



                  In terms of doing it automatically on route changes, as of now there's no built-in way of doing this other than subscribing to Router and calling setTitle() in your callback:



                  import {RouteConfig} from 'angular2/router';
                  import {Title} from 'angular2/platform/browser';

                  @RouteConfig([
                  {path: '/home', component: HomeCmp, name: 'HomeCmp' }
                  ])
                  class MyApp {
                  constructor(router:Router, title:Title) {
                  router.events.subscribe((event)=>{ //fires on every URL change
                  title.setTitle(getTitleFor(router.url));
                  });
                  }
                  }


                  That said, I emphasize as of now because the router is still under heavy development, and I expect (or at least hope) that we'll be able to do this via RouteConfig in the final release.



                  EDIT:



                  As of the release of Angular 2 (2.0.0), a few things have changed:




                  • The docs for the Title service are now here: https://angular.io/docs/ts/latest/api/platform-browser/index/Title-class.html

                  • The service is imported from '@angular/platform-browser'







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 5 '17 at 19:30









                  adamdport

                  4,05063463




                  4,05063463










                  answered Jan 5 '16 at 5:31









                  drewmooredrewmoore

                  19.3k1566100




                  19.3k1566100








                  • 3





                    Also router.subscribe is now router.events.subscribe in Angular2

                    – Romesh
                    Dec 7 '16 at 10:41








                  • 1





                    getTitleFor(url) this method returns what ? i.e value of name in router config ?

                    – Kaleem Ullah
                    Feb 2 '17 at 9:24











                  • If I'm reading the docs correctly, getTitleFor() is no longer a thing.

                    – Brendan
                    Feb 17 '17 at 18:23






                  • 1





                    I found this answer to be a bit more detailed

                    – adamdport
                    Jul 5 '17 at 19:53














                  • 3





                    Also router.subscribe is now router.events.subscribe in Angular2

                    – Romesh
                    Dec 7 '16 at 10:41








                  • 1





                    getTitleFor(url) this method returns what ? i.e value of name in router config ?

                    – Kaleem Ullah
                    Feb 2 '17 at 9:24











                  • If I'm reading the docs correctly, getTitleFor() is no longer a thing.

                    – Brendan
                    Feb 17 '17 at 18:23






                  • 1





                    I found this answer to be a bit more detailed

                    – adamdport
                    Jul 5 '17 at 19:53








                  3




                  3





                  Also router.subscribe is now router.events.subscribe in Angular2

                  – Romesh
                  Dec 7 '16 at 10:41







                  Also router.subscribe is now router.events.subscribe in Angular2

                  – Romesh
                  Dec 7 '16 at 10:41






                  1




                  1





                  getTitleFor(url) this method returns what ? i.e value of name in router config ?

                  – Kaleem Ullah
                  Feb 2 '17 at 9:24





                  getTitleFor(url) this method returns what ? i.e value of name in router config ?

                  – Kaleem Ullah
                  Feb 2 '17 at 9:24













                  If I'm reading the docs correctly, getTitleFor() is no longer a thing.

                  – Brendan
                  Feb 17 '17 at 18:23





                  If I'm reading the docs correctly, getTitleFor() is no longer a thing.

                  – Brendan
                  Feb 17 '17 at 18:23




                  1




                  1





                  I found this answer to be a bit more detailed

                  – adamdport
                  Jul 5 '17 at 19:53





                  I found this answer to be a bit more detailed

                  – adamdport
                  Jul 5 '17 at 19:53













                  15














                  Here's my approach which works fine, especially for nested routes:



                  I use a recursive helper method to grab the deepest available title after a route has changed:



                  @Component({
                  selector: 'app',
                  template: `
                  <h1>{{title | async}}</h1>
                  <router-outlet></router-outlet>
                  `
                  })
                  export class AppComponent {
                  constructor(private router: Router) {
                  this.title = this.router.events
                  .filter((event) => event instanceof NavigationEnd)
                  .map(() => this.getDeepestTitle(this.router.routerState.snapshot.root));
                  }

                  title: Observable<string>;

                  private getDeepestTitle(routeSnapshot: ActivatedRouteSnapshot) {
                  var title = routeSnapshot.data ? routeSnapshot.data['title'] : '';
                  if (routeSnapshot.firstChild) {
                  title = this.getDeepestTitle(routeSnapshot.firstChild) || title;
                  }
                  return title;
                  }
                  }


                  This is assuming, that you have assigned page titles within the data property of your routes, like this:



                  {
                  path: 'example',
                  component: ExampleComponent,
                  data: {
                  title: 'Some Page'
                  }
                  }





                  share|improve this answer


























                  • I was looking for the data property at router.routeSnapshot.root.data, but it appears that it can be nested based on how the route is setup. This answer worked for me.

                    – The Muffin Man
                    Feb 16 '17 at 20:57











                  • I had to add this.title = this.getDeepestTitle(this.activatedRoute.snapshot.root); for this to work on the first visit.

                    – Mel
                    Jan 23 '18 at 15:54
















                  15














                  Here's my approach which works fine, especially for nested routes:



                  I use a recursive helper method to grab the deepest available title after a route has changed:



                  @Component({
                  selector: 'app',
                  template: `
                  <h1>{{title | async}}</h1>
                  <router-outlet></router-outlet>
                  `
                  })
                  export class AppComponent {
                  constructor(private router: Router) {
                  this.title = this.router.events
                  .filter((event) => event instanceof NavigationEnd)
                  .map(() => this.getDeepestTitle(this.router.routerState.snapshot.root));
                  }

                  title: Observable<string>;

                  private getDeepestTitle(routeSnapshot: ActivatedRouteSnapshot) {
                  var title = routeSnapshot.data ? routeSnapshot.data['title'] : '';
                  if (routeSnapshot.firstChild) {
                  title = this.getDeepestTitle(routeSnapshot.firstChild) || title;
                  }
                  return title;
                  }
                  }


                  This is assuming, that you have assigned page titles within the data property of your routes, like this:



                  {
                  path: 'example',
                  component: ExampleComponent,
                  data: {
                  title: 'Some Page'
                  }
                  }





                  share|improve this answer


























                  • I was looking for the data property at router.routeSnapshot.root.data, but it appears that it can be nested based on how the route is setup. This answer worked for me.

                    – The Muffin Man
                    Feb 16 '17 at 20:57











                  • I had to add this.title = this.getDeepestTitle(this.activatedRoute.snapshot.root); for this to work on the first visit.

                    – Mel
                    Jan 23 '18 at 15:54














                  15












                  15








                  15







                  Here's my approach which works fine, especially for nested routes:



                  I use a recursive helper method to grab the deepest available title after a route has changed:



                  @Component({
                  selector: 'app',
                  template: `
                  <h1>{{title | async}}</h1>
                  <router-outlet></router-outlet>
                  `
                  })
                  export class AppComponent {
                  constructor(private router: Router) {
                  this.title = this.router.events
                  .filter((event) => event instanceof NavigationEnd)
                  .map(() => this.getDeepestTitle(this.router.routerState.snapshot.root));
                  }

                  title: Observable<string>;

                  private getDeepestTitle(routeSnapshot: ActivatedRouteSnapshot) {
                  var title = routeSnapshot.data ? routeSnapshot.data['title'] : '';
                  if (routeSnapshot.firstChild) {
                  title = this.getDeepestTitle(routeSnapshot.firstChild) || title;
                  }
                  return title;
                  }
                  }


                  This is assuming, that you have assigned page titles within the data property of your routes, like this:



                  {
                  path: 'example',
                  component: ExampleComponent,
                  data: {
                  title: 'Some Page'
                  }
                  }





                  share|improve this answer















                  Here's my approach which works fine, especially for nested routes:



                  I use a recursive helper method to grab the deepest available title after a route has changed:



                  @Component({
                  selector: 'app',
                  template: `
                  <h1>{{title | async}}</h1>
                  <router-outlet></router-outlet>
                  `
                  })
                  export class AppComponent {
                  constructor(private router: Router) {
                  this.title = this.router.events
                  .filter((event) => event instanceof NavigationEnd)
                  .map(() => this.getDeepestTitle(this.router.routerState.snapshot.root));
                  }

                  title: Observable<string>;

                  private getDeepestTitle(routeSnapshot: ActivatedRouteSnapshot) {
                  var title = routeSnapshot.data ? routeSnapshot.data['title'] : '';
                  if (routeSnapshot.firstChild) {
                  title = this.getDeepestTitle(routeSnapshot.firstChild) || title;
                  }
                  return title;
                  }
                  }


                  This is assuming, that you have assigned page titles within the data property of your routes, like this:



                  {
                  path: 'example',
                  component: ExampleComponent,
                  data: {
                  title: 'Some Page'
                  }
                  }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jun 12 '17 at 17:28

























                  answered Nov 7 '16 at 14:59









                  Martin CremerMartin Cremer

                  1,7951522




                  1,7951522













                  • I was looking for the data property at router.routeSnapshot.root.data, but it appears that it can be nested based on how the route is setup. This answer worked for me.

                    – The Muffin Man
                    Feb 16 '17 at 20:57











                  • I had to add this.title = this.getDeepestTitle(this.activatedRoute.snapshot.root); for this to work on the first visit.

                    – Mel
                    Jan 23 '18 at 15:54



















                  • I was looking for the data property at router.routeSnapshot.root.data, but it appears that it can be nested based on how the route is setup. This answer worked for me.

                    – The Muffin Man
                    Feb 16 '17 at 20:57











                  • I had to add this.title = this.getDeepestTitle(this.activatedRoute.snapshot.root); for this to work on the first visit.

                    – Mel
                    Jan 23 '18 at 15:54

















                  I was looking for the data property at router.routeSnapshot.root.data, but it appears that it can be nested based on how the route is setup. This answer worked for me.

                  – The Muffin Man
                  Feb 16 '17 at 20:57





                  I was looking for the data property at router.routeSnapshot.root.data, but it appears that it can be nested based on how the route is setup. This answer worked for me.

                  – The Muffin Man
                  Feb 16 '17 at 20:57













                  I had to add this.title = this.getDeepestTitle(this.activatedRoute.snapshot.root); for this to work on the first visit.

                  – Mel
                  Jan 23 '18 at 15:54





                  I had to add this.title = this.getDeepestTitle(this.activatedRoute.snapshot.root); for this to work on the first visit.

                  – Mel
                  Jan 23 '18 at 15:54











                  13














                  For Angular 4+:



                  If you want to use route custom data to define page title for every route path, the following approach will work for the nested routes and with angular version 4+:



                  You can pass page title in your route definition:



                    {path: 'home', component: DashboardComponent, data: {title: 'Home Pag'}},
                  {path: 'about', component: AboutUsComponent, data: {title: 'About Us Page'}},
                  {path: 'contact', component: ContactUsComponent, data: {title: 'Contact Us Pag'}},


                  Now, most important in your upper level component (ie AppComponent), you can globally catch the route custom data on every route change and update the page title:



                  import {Title} from "@angular/platform-browser";
                  export class AppComponent implements OnInit {

                  constructor(
                  private activatedRoute: ActivatedRoute,
                  private router: Router,
                  private titleService: Title
                  ) { }

                  ngOnInit() {
                  this.router
                  .events
                  .filter(event => event instanceof NavigationEnd)
                  .map(() => {
                  let child = this.activatedRoute.firstChild;
                  while (child) {
                  if (child.firstChild) {
                  child = child.firstChild;
                  } else if (child.snapshot.data && child.snapshot.data['title']) {
                  return child.snapshot.data['title'];
                  } else {
                  return null;
                  }
                  }
                  return null;
                  }).subscribe( (title: any) => {
                  this.titleService.setTitle(title);
                  });
                  }
                  }


                  The above code is tested against angular verion 4+.






                  share|improve this answer



















                  • 1





                    Great! Just some more additions. Be sure to add import { BrowserModule, Title } from '@angular/platform-browser'; and set the providers: [Title] in the Module, and also have to add import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; in the Component. Otherwise you can get some errors.

                    – BogdanD
                    Apr 13 '18 at 8:43


















                  13














                  For Angular 4+:



                  If you want to use route custom data to define page title for every route path, the following approach will work for the nested routes and with angular version 4+:



                  You can pass page title in your route definition:



                    {path: 'home', component: DashboardComponent, data: {title: 'Home Pag'}},
                  {path: 'about', component: AboutUsComponent, data: {title: 'About Us Page'}},
                  {path: 'contact', component: ContactUsComponent, data: {title: 'Contact Us Pag'}},


                  Now, most important in your upper level component (ie AppComponent), you can globally catch the route custom data on every route change and update the page title:



                  import {Title} from "@angular/platform-browser";
                  export class AppComponent implements OnInit {

                  constructor(
                  private activatedRoute: ActivatedRoute,
                  private router: Router,
                  private titleService: Title
                  ) { }

                  ngOnInit() {
                  this.router
                  .events
                  .filter(event => event instanceof NavigationEnd)
                  .map(() => {
                  let child = this.activatedRoute.firstChild;
                  while (child) {
                  if (child.firstChild) {
                  child = child.firstChild;
                  } else if (child.snapshot.data && child.snapshot.data['title']) {
                  return child.snapshot.data['title'];
                  } else {
                  return null;
                  }
                  }
                  return null;
                  }).subscribe( (title: any) => {
                  this.titleService.setTitle(title);
                  });
                  }
                  }


                  The above code is tested against angular verion 4+.






                  share|improve this answer



















                  • 1





                    Great! Just some more additions. Be sure to add import { BrowserModule, Title } from '@angular/platform-browser'; and set the providers: [Title] in the Module, and also have to add import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; in the Component. Otherwise you can get some errors.

                    – BogdanD
                    Apr 13 '18 at 8:43
















                  13












                  13








                  13







                  For Angular 4+:



                  If you want to use route custom data to define page title for every route path, the following approach will work for the nested routes and with angular version 4+:



                  You can pass page title in your route definition:



                    {path: 'home', component: DashboardComponent, data: {title: 'Home Pag'}},
                  {path: 'about', component: AboutUsComponent, data: {title: 'About Us Page'}},
                  {path: 'contact', component: ContactUsComponent, data: {title: 'Contact Us Pag'}},


                  Now, most important in your upper level component (ie AppComponent), you can globally catch the route custom data on every route change and update the page title:



                  import {Title} from "@angular/platform-browser";
                  export class AppComponent implements OnInit {

                  constructor(
                  private activatedRoute: ActivatedRoute,
                  private router: Router,
                  private titleService: Title
                  ) { }

                  ngOnInit() {
                  this.router
                  .events
                  .filter(event => event instanceof NavigationEnd)
                  .map(() => {
                  let child = this.activatedRoute.firstChild;
                  while (child) {
                  if (child.firstChild) {
                  child = child.firstChild;
                  } else if (child.snapshot.data && child.snapshot.data['title']) {
                  return child.snapshot.data['title'];
                  } else {
                  return null;
                  }
                  }
                  return null;
                  }).subscribe( (title: any) => {
                  this.titleService.setTitle(title);
                  });
                  }
                  }


                  The above code is tested against angular verion 4+.






                  share|improve this answer













                  For Angular 4+:



                  If you want to use route custom data to define page title for every route path, the following approach will work for the nested routes and with angular version 4+:



                  You can pass page title in your route definition:



                    {path: 'home', component: DashboardComponent, data: {title: 'Home Pag'}},
                  {path: 'about', component: AboutUsComponent, data: {title: 'About Us Page'}},
                  {path: 'contact', component: ContactUsComponent, data: {title: 'Contact Us Pag'}},


                  Now, most important in your upper level component (ie AppComponent), you can globally catch the route custom data on every route change and update the page title:



                  import {Title} from "@angular/platform-browser";
                  export class AppComponent implements OnInit {

                  constructor(
                  private activatedRoute: ActivatedRoute,
                  private router: Router,
                  private titleService: Title
                  ) { }

                  ngOnInit() {
                  this.router
                  .events
                  .filter(event => event instanceof NavigationEnd)
                  .map(() => {
                  let child = this.activatedRoute.firstChild;
                  while (child) {
                  if (child.firstChild) {
                  child = child.firstChild;
                  } else if (child.snapshot.data && child.snapshot.data['title']) {
                  return child.snapshot.data['title'];
                  } else {
                  return null;
                  }
                  }
                  return null;
                  }).subscribe( (title: any) => {
                  this.titleService.setTitle(title);
                  });
                  }
                  }


                  The above code is tested against angular verion 4+.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Oct 11 '17 at 21:42









                  asmmahmudasmmahmud

                  2,4211827




                  2,4211827








                  • 1





                    Great! Just some more additions. Be sure to add import { BrowserModule, Title } from '@angular/platform-browser'; and set the providers: [Title] in the Module, and also have to add import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; in the Component. Otherwise you can get some errors.

                    – BogdanD
                    Apr 13 '18 at 8:43
















                  • 1





                    Great! Just some more additions. Be sure to add import { BrowserModule, Title } from '@angular/platform-browser'; and set the providers: [Title] in the Module, and also have to add import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; in the Component. Otherwise you can get some errors.

                    – BogdanD
                    Apr 13 '18 at 8:43










                  1




                  1





                  Great! Just some more additions. Be sure to add import { BrowserModule, Title } from '@angular/platform-browser'; and set the providers: [Title] in the Module, and also have to add import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; in the Component. Otherwise you can get some errors.

                  – BogdanD
                  Apr 13 '18 at 8:43







                  Great! Just some more additions. Be sure to add import { BrowserModule, Title } from '@angular/platform-browser'; and set the providers: [Title] in the Module, and also have to add import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; in the Component. Otherwise you can get some errors.

                  – BogdanD
                  Apr 13 '18 at 8:43













                  8














                  Its really very easy to do this, you can follow therse steps to see the immediate effects:



                  we provide the Title service in bootstrap:



                  import { NgModule } from '@angular/core';
                  import { BrowserModule, Title } from '@angular/platform-browser';

                  import { AppComponent } from './app.component';

                  @NgModule({
                  imports: [
                  BrowserModule
                  ],
                  declarations: [
                  AppComponent
                  ],
                  providers: [
                  Title
                  ],
                  bootstrap: [ AppComponent ]
                  })
                  export class AppModule { }


                  Then import this service in the component you want:



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

                  @Component({
                  selector: 'my-app',
                  template:
                  `<p>
                  Select a title to set on the current HTML document:
                  </p>

                  <ul>
                  <li><a (click)="setTitle( 'Good morning!' )">Good morning</a>.</li>
                  <li><a (click)="setTitle( 'Good afternoon!' )">Good afternoon</a>.</li>
                  <li><a (click)="setTitle( 'Good evening!' )">Good evening</a>.</li>
                  </ul>
                  `
                  })
                  export class AppComponent {
                  public constructor(private titleService: Title ) { }

                  public setTitle( newTitle: string) {
                  this.titleService.setTitle( newTitle );
                  }
                  }


                  now click on those links to see the title changing.



                  you can also use ng2-meta for changing page title and description as well,you can refer to this link:



                  https://github.com/vinaygopinath/ng2-meta






                  share|improve this answer


























                  • yeah superb answer, using this we can change title and description as well , No need to use Title service of angular2 extra in your code, thanks for answer.

                    – Pardeep Jain
                    Jan 31 '17 at 7:49











                  • @PardeepJain Will this solution work even though my app takes 4 seconds to load? I've used ng2-meta and that doesn't work because of my app loading time. (I've tried everything to reduce the loading time)

                    – AngularM
                    Feb 8 '17 at 11:20








                  • 2





                    What if user enter the page url and press enter OR Refresh the page, will it work. I can see you copy the same code from document :) angular.io/docs/ts/latest/cookbook/set-document-title.html

                    – Ali Adravi
                    Apr 14 '17 at 0:05


















                  8














                  Its really very easy to do this, you can follow therse steps to see the immediate effects:



                  we provide the Title service in bootstrap:



                  import { NgModule } from '@angular/core';
                  import { BrowserModule, Title } from '@angular/platform-browser';

                  import { AppComponent } from './app.component';

                  @NgModule({
                  imports: [
                  BrowserModule
                  ],
                  declarations: [
                  AppComponent
                  ],
                  providers: [
                  Title
                  ],
                  bootstrap: [ AppComponent ]
                  })
                  export class AppModule { }


                  Then import this service in the component you want:



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

                  @Component({
                  selector: 'my-app',
                  template:
                  `<p>
                  Select a title to set on the current HTML document:
                  </p>

                  <ul>
                  <li><a (click)="setTitle( 'Good morning!' )">Good morning</a>.</li>
                  <li><a (click)="setTitle( 'Good afternoon!' )">Good afternoon</a>.</li>
                  <li><a (click)="setTitle( 'Good evening!' )">Good evening</a>.</li>
                  </ul>
                  `
                  })
                  export class AppComponent {
                  public constructor(private titleService: Title ) { }

                  public setTitle( newTitle: string) {
                  this.titleService.setTitle( newTitle );
                  }
                  }


                  now click on those links to see the title changing.



                  you can also use ng2-meta for changing page title and description as well,you can refer to this link:



                  https://github.com/vinaygopinath/ng2-meta






                  share|improve this answer


























                  • yeah superb answer, using this we can change title and description as well , No need to use Title service of angular2 extra in your code, thanks for answer.

                    – Pardeep Jain
                    Jan 31 '17 at 7:49











                  • @PardeepJain Will this solution work even though my app takes 4 seconds to load? I've used ng2-meta and that doesn't work because of my app loading time. (I've tried everything to reduce the loading time)

                    – AngularM
                    Feb 8 '17 at 11:20








                  • 2





                    What if user enter the page url and press enter OR Refresh the page, will it work. I can see you copy the same code from document :) angular.io/docs/ts/latest/cookbook/set-document-title.html

                    – Ali Adravi
                    Apr 14 '17 at 0:05
















                  8












                  8








                  8







                  Its really very easy to do this, you can follow therse steps to see the immediate effects:



                  we provide the Title service in bootstrap:



                  import { NgModule } from '@angular/core';
                  import { BrowserModule, Title } from '@angular/platform-browser';

                  import { AppComponent } from './app.component';

                  @NgModule({
                  imports: [
                  BrowserModule
                  ],
                  declarations: [
                  AppComponent
                  ],
                  providers: [
                  Title
                  ],
                  bootstrap: [ AppComponent ]
                  })
                  export class AppModule { }


                  Then import this service in the component you want:



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

                  @Component({
                  selector: 'my-app',
                  template:
                  `<p>
                  Select a title to set on the current HTML document:
                  </p>

                  <ul>
                  <li><a (click)="setTitle( 'Good morning!' )">Good morning</a>.</li>
                  <li><a (click)="setTitle( 'Good afternoon!' )">Good afternoon</a>.</li>
                  <li><a (click)="setTitle( 'Good evening!' )">Good evening</a>.</li>
                  </ul>
                  `
                  })
                  export class AppComponent {
                  public constructor(private titleService: Title ) { }

                  public setTitle( newTitle: string) {
                  this.titleService.setTitle( newTitle );
                  }
                  }


                  now click on those links to see the title changing.



                  you can also use ng2-meta for changing page title and description as well,you can refer to this link:



                  https://github.com/vinaygopinath/ng2-meta






                  share|improve this answer















                  Its really very easy to do this, you can follow therse steps to see the immediate effects:



                  we provide the Title service in bootstrap:



                  import { NgModule } from '@angular/core';
                  import { BrowserModule, Title } from '@angular/platform-browser';

                  import { AppComponent } from './app.component';

                  @NgModule({
                  imports: [
                  BrowserModule
                  ],
                  declarations: [
                  AppComponent
                  ],
                  providers: [
                  Title
                  ],
                  bootstrap: [ AppComponent ]
                  })
                  export class AppModule { }


                  Then import this service in the component you want:



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

                  @Component({
                  selector: 'my-app',
                  template:
                  `<p>
                  Select a title to set on the current HTML document:
                  </p>

                  <ul>
                  <li><a (click)="setTitle( 'Good morning!' )">Good morning</a>.</li>
                  <li><a (click)="setTitle( 'Good afternoon!' )">Good afternoon</a>.</li>
                  <li><a (click)="setTitle( 'Good evening!' )">Good evening</a>.</li>
                  </ul>
                  `
                  })
                  export class AppComponent {
                  public constructor(private titleService: Title ) { }

                  public setTitle( newTitle: string) {
                  this.titleService.setTitle( newTitle );
                  }
                  }


                  now click on those links to see the title changing.



                  you can also use ng2-meta for changing page title and description as well,you can refer to this link:



                  https://github.com/vinaygopinath/ng2-meta







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 31 '17 at 7:23

























                  answered Jan 31 '17 at 6:53









                  Shailesh kalaShailesh kala

                  678910




                  678910













                  • yeah superb answer, using this we can change title and description as well , No need to use Title service of angular2 extra in your code, thanks for answer.

                    – Pardeep Jain
                    Jan 31 '17 at 7:49











                  • @PardeepJain Will this solution work even though my app takes 4 seconds to load? I've used ng2-meta and that doesn't work because of my app loading time. (I've tried everything to reduce the loading time)

                    – AngularM
                    Feb 8 '17 at 11:20








                  • 2





                    What if user enter the page url and press enter OR Refresh the page, will it work. I can see you copy the same code from document :) angular.io/docs/ts/latest/cookbook/set-document-title.html

                    – Ali Adravi
                    Apr 14 '17 at 0:05





















                  • yeah superb answer, using this we can change title and description as well , No need to use Title service of angular2 extra in your code, thanks for answer.

                    – Pardeep Jain
                    Jan 31 '17 at 7:49











                  • @PardeepJain Will this solution work even though my app takes 4 seconds to load? I've used ng2-meta and that doesn't work because of my app loading time. (I've tried everything to reduce the loading time)

                    – AngularM
                    Feb 8 '17 at 11:20








                  • 2





                    What if user enter the page url and press enter OR Refresh the page, will it work. I can see you copy the same code from document :) angular.io/docs/ts/latest/cookbook/set-document-title.html

                    – Ali Adravi
                    Apr 14 '17 at 0:05



















                  yeah superb answer, using this we can change title and description as well , No need to use Title service of angular2 extra in your code, thanks for answer.

                  – Pardeep Jain
                  Jan 31 '17 at 7:49





                  yeah superb answer, using this we can change title and description as well , No need to use Title service of angular2 extra in your code, thanks for answer.

                  – Pardeep Jain
                  Jan 31 '17 at 7:49













                  @PardeepJain Will this solution work even though my app takes 4 seconds to load? I've used ng2-meta and that doesn't work because of my app loading time. (I've tried everything to reduce the loading time)

                  – AngularM
                  Feb 8 '17 at 11:20







                  @PardeepJain Will this solution work even though my app takes 4 seconds to load? I've used ng2-meta and that doesn't work because of my app loading time. (I've tried everything to reduce the loading time)

                  – AngularM
                  Feb 8 '17 at 11:20






                  2




                  2





                  What if user enter the page url and press enter OR Refresh the page, will it work. I can see you copy the same code from document :) angular.io/docs/ts/latest/cookbook/set-document-title.html

                  – Ali Adravi
                  Apr 14 '17 at 0:05







                  What if user enter the page url and press enter OR Refresh the page, will it work. I can see you copy the same code from document :) angular.io/docs/ts/latest/cookbook/set-document-title.html

                  – Ali Adravi
                  Apr 14 '17 at 0:05













                  5














                  Angular 2 provides a Title Service see Shailesh answer is just copy of that code.



                  I our app.module.ts



                  import { BrowserModule, Title } from '@angular/platform-browser';
                  ........
                  providers: [..., Title],
                  bootstrap: [AppComponent]


                  Now move to our app.component.ts



                  import { Title }     from '@angular/platform-browser';
                  ......
                  export class AppComponent {

                  public constructor(private titleService: Title ) { }

                  public setTitle( newTitle: string) {
                  this.titleService.setTitle( newTitle );
                  }
                  }


                  Put the title tag on your component html and it will read and set for you.



                  If you want to know how to set it dynamically and further detail see this article






                  share|improve this answer




























                    5














                    Angular 2 provides a Title Service see Shailesh answer is just copy of that code.



                    I our app.module.ts



                    import { BrowserModule, Title } from '@angular/platform-browser';
                    ........
                    providers: [..., Title],
                    bootstrap: [AppComponent]


                    Now move to our app.component.ts



                    import { Title }     from '@angular/platform-browser';
                    ......
                    export class AppComponent {

                    public constructor(private titleService: Title ) { }

                    public setTitle( newTitle: string) {
                    this.titleService.setTitle( newTitle );
                    }
                    }


                    Put the title tag on your component html and it will read and set for you.



                    If you want to know how to set it dynamically and further detail see this article






                    share|improve this answer


























                      5












                      5








                      5







                      Angular 2 provides a Title Service see Shailesh answer is just copy of that code.



                      I our app.module.ts



                      import { BrowserModule, Title } from '@angular/platform-browser';
                      ........
                      providers: [..., Title],
                      bootstrap: [AppComponent]


                      Now move to our app.component.ts



                      import { Title }     from '@angular/platform-browser';
                      ......
                      export class AppComponent {

                      public constructor(private titleService: Title ) { }

                      public setTitle( newTitle: string) {
                      this.titleService.setTitle( newTitle );
                      }
                      }


                      Put the title tag on your component html and it will read and set for you.



                      If you want to know how to set it dynamically and further detail see this article






                      share|improve this answer













                      Angular 2 provides a Title Service see Shailesh answer is just copy of that code.



                      I our app.module.ts



                      import { BrowserModule, Title } from '@angular/platform-browser';
                      ........
                      providers: [..., Title],
                      bootstrap: [AppComponent]


                      Now move to our app.component.ts



                      import { Title }     from '@angular/platform-browser';
                      ......
                      export class AppComponent {

                      public constructor(private titleService: Title ) { }

                      public setTitle( newTitle: string) {
                      this.titleService.setTitle( newTitle );
                      }
                      }


                      Put the title tag on your component html and it will read and set for you.



                      If you want to know how to set it dynamically and further detail see this article







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Apr 14 '17 at 1:28









                      Ali AdraviAli Adravi

                      12.7k45767




                      12.7k45767























                          2














                          This is what I went with:



                          constructor(private router: Router, private title: Title) { }

                          ngOnInit() {
                          this.router.events.subscribe(event => {
                          if (event instanceof NavigationEnd) {
                          this.title.setTitle(this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).join(' - '));
                          }
                          });
                          }

                          recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
                          var titleParts = <string>;
                          if (snapshot) {
                          if (snapshot.firstChild) {
                          titleParts = titleParts.concat(this.recursivelyGenerateTitle(snapshot.firstChild));
                          }

                          if (snapshot.data['title']) {
                          titleParts.push(snapshot.data['title']);
                          }
                          }

                          return titleParts;
                          }





                          share|improve this answer
























                          • Fantastic, only tweak I made was to ensure a title on the HTML document and tweaked this line of your code (note the reverse()), this.title.setTitle(this.title.getTitle().split(' - ')[0] + ' - ' + this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).reverse().join(' - '));.

                            – Tim Harker
                            Apr 28 '17 at 1:40








                          • 1





                            Or alternatively, you could use unshift() instead of push() and then reverse().

                            – Tim Harker
                            Apr 28 '17 at 1:49
















                          2














                          This is what I went with:



                          constructor(private router: Router, private title: Title) { }

                          ngOnInit() {
                          this.router.events.subscribe(event => {
                          if (event instanceof NavigationEnd) {
                          this.title.setTitle(this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).join(' - '));
                          }
                          });
                          }

                          recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
                          var titleParts = <string>;
                          if (snapshot) {
                          if (snapshot.firstChild) {
                          titleParts = titleParts.concat(this.recursivelyGenerateTitle(snapshot.firstChild));
                          }

                          if (snapshot.data['title']) {
                          titleParts.push(snapshot.data['title']);
                          }
                          }

                          return titleParts;
                          }





                          share|improve this answer
























                          • Fantastic, only tweak I made was to ensure a title on the HTML document and tweaked this line of your code (note the reverse()), this.title.setTitle(this.title.getTitle().split(' - ')[0] + ' - ' + this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).reverse().join(' - '));.

                            – Tim Harker
                            Apr 28 '17 at 1:40








                          • 1





                            Or alternatively, you could use unshift() instead of push() and then reverse().

                            – Tim Harker
                            Apr 28 '17 at 1:49














                          2












                          2








                          2







                          This is what I went with:



                          constructor(private router: Router, private title: Title) { }

                          ngOnInit() {
                          this.router.events.subscribe(event => {
                          if (event instanceof NavigationEnd) {
                          this.title.setTitle(this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).join(' - '));
                          }
                          });
                          }

                          recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
                          var titleParts = <string>;
                          if (snapshot) {
                          if (snapshot.firstChild) {
                          titleParts = titleParts.concat(this.recursivelyGenerateTitle(snapshot.firstChild));
                          }

                          if (snapshot.data['title']) {
                          titleParts.push(snapshot.data['title']);
                          }
                          }

                          return titleParts;
                          }





                          share|improve this answer













                          This is what I went with:



                          constructor(private router: Router, private title: Title) { }

                          ngOnInit() {
                          this.router.events.subscribe(event => {
                          if (event instanceof NavigationEnd) {
                          this.title.setTitle(this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).join(' - '));
                          }
                          });
                          }

                          recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
                          var titleParts = <string>;
                          if (snapshot) {
                          if (snapshot.firstChild) {
                          titleParts = titleParts.concat(this.recursivelyGenerateTitle(snapshot.firstChild));
                          }

                          if (snapshot.data['title']) {
                          titleParts.push(snapshot.data['title']);
                          }
                          }

                          return titleParts;
                          }






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 2 '17 at 22:19









                          JohnJohn

                          9,633135274




                          9,633135274













                          • Fantastic, only tweak I made was to ensure a title on the HTML document and tweaked this line of your code (note the reverse()), this.title.setTitle(this.title.getTitle().split(' - ')[0] + ' - ' + this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).reverse().join(' - '));.

                            – Tim Harker
                            Apr 28 '17 at 1:40








                          • 1





                            Or alternatively, you could use unshift() instead of push() and then reverse().

                            – Tim Harker
                            Apr 28 '17 at 1:49



















                          • Fantastic, only tweak I made was to ensure a title on the HTML document and tweaked this line of your code (note the reverse()), this.title.setTitle(this.title.getTitle().split(' - ')[0] + ' - ' + this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).reverse().join(' - '));.

                            – Tim Harker
                            Apr 28 '17 at 1:40








                          • 1





                            Or alternatively, you could use unshift() instead of push() and then reverse().

                            – Tim Harker
                            Apr 28 '17 at 1:49

















                          Fantastic, only tweak I made was to ensure a title on the HTML document and tweaked this line of your code (note the reverse()), this.title.setTitle(this.title.getTitle().split(' - ')[0] + ' - ' + this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).reverse().join(' - '));.

                          – Tim Harker
                          Apr 28 '17 at 1:40







                          Fantastic, only tweak I made was to ensure a title on the HTML document and tweaked this line of your code (note the reverse()), this.title.setTitle(this.title.getTitle().split(' - ')[0] + ' - ' + this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).reverse().join(' - '));.

                          – Tim Harker
                          Apr 28 '17 at 1:40






                          1




                          1





                          Or alternatively, you could use unshift() instead of push() and then reverse().

                          – Tim Harker
                          Apr 28 '17 at 1:49





                          Or alternatively, you could use unshift() instead of push() and then reverse().

                          – Tim Harker
                          Apr 28 '17 at 1:49











                          1














                          import {Title} from "@angular/platform-browser"; 
                          @Component({
                          selector: 'app',
                          templateUrl: './app.component.html',
                          providers : [Title]
                          })

                          export class AppComponent implements {
                          constructor( private title: Title) {
                          this.title.setTitle('page title changed');
                          }
                          }





                          share|improve this answer




























                            1














                            import {Title} from "@angular/platform-browser"; 
                            @Component({
                            selector: 'app',
                            templateUrl: './app.component.html',
                            providers : [Title]
                            })

                            export class AppComponent implements {
                            constructor( private title: Title) {
                            this.title.setTitle('page title changed');
                            }
                            }





                            share|improve this answer


























                              1












                              1








                              1







                              import {Title} from "@angular/platform-browser"; 
                              @Component({
                              selector: 'app',
                              templateUrl: './app.component.html',
                              providers : [Title]
                              })

                              export class AppComponent implements {
                              constructor( private title: Title) {
                              this.title.setTitle('page title changed');
                              }
                              }





                              share|improve this answer













                              import {Title} from "@angular/platform-browser"; 
                              @Component({
                              selector: 'app',
                              templateUrl: './app.component.html',
                              providers : [Title]
                              })

                              export class AppComponent implements {
                              constructor( private title: Title) {
                              this.title.setTitle('page title changed');
                              }
                              }






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jan 31 '17 at 7:32









                              Yoav SchniedermanYoav Schniederman

                              2,50711226




                              2,50711226























                                  1














                                  Here's the simplest way to change the Title of the page, when pages/views are navigated (Tested as of Angular @2.3.1). Simply apply the following solution to all the views you have and you should be good to go:



                                  Example Code in About Us page/view:



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

                                  export class AboutUsComponent implements OnInit {

                                  constructor(private _titleService: Title) {
                                  }

                                  ngOnInit() {
                                  //Set page Title when this view is initialized
                                  this._titleService.setTitle('About Us');
                                  }

                                  }


                                  Example Code in Contact Us page/view:



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

                                  export class ContactusComponent implements OnInit {

                                  constructor(private _titleService: Title) {
                                  }

                                  ngOnInit() {
                                  //Set page Title
                                  this._titleService.setTitle('Contact Us');
                                  }

                                  }





                                  share|improve this answer




























                                    1














                                    Here's the simplest way to change the Title of the page, when pages/views are navigated (Tested as of Angular @2.3.1). Simply apply the following solution to all the views you have and you should be good to go:



                                    Example Code in About Us page/view:



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

                                    export class AboutUsComponent implements OnInit {

                                    constructor(private _titleService: Title) {
                                    }

                                    ngOnInit() {
                                    //Set page Title when this view is initialized
                                    this._titleService.setTitle('About Us');
                                    }

                                    }


                                    Example Code in Contact Us page/view:



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

                                    export class ContactusComponent implements OnInit {

                                    constructor(private _titleService: Title) {
                                    }

                                    ngOnInit() {
                                    //Set page Title
                                    this._titleService.setTitle('Contact Us');
                                    }

                                    }





                                    share|improve this answer


























                                      1












                                      1








                                      1







                                      Here's the simplest way to change the Title of the page, when pages/views are navigated (Tested as of Angular @2.3.1). Simply apply the following solution to all the views you have and you should be good to go:



                                      Example Code in About Us page/view:



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

                                      export class AboutUsComponent implements OnInit {

                                      constructor(private _titleService: Title) {
                                      }

                                      ngOnInit() {
                                      //Set page Title when this view is initialized
                                      this._titleService.setTitle('About Us');
                                      }

                                      }


                                      Example Code in Contact Us page/view:



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

                                      export class ContactusComponent implements OnInit {

                                      constructor(private _titleService: Title) {
                                      }

                                      ngOnInit() {
                                      //Set page Title
                                      this._titleService.setTitle('Contact Us');
                                      }

                                      }





                                      share|improve this answer













                                      Here's the simplest way to change the Title of the page, when pages/views are navigated (Tested as of Angular @2.3.1). Simply apply the following solution to all the views you have and you should be good to go:



                                      Example Code in About Us page/view:



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

                                      export class AboutUsComponent implements OnInit {

                                      constructor(private _titleService: Title) {
                                      }

                                      ngOnInit() {
                                      //Set page Title when this view is initialized
                                      this._titleService.setTitle('About Us');
                                      }

                                      }


                                      Example Code in Contact Us page/view:



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

                                      export class ContactusComponent implements OnInit {

                                      constructor(private _titleService: Title) {
                                      }

                                      ngOnInit() {
                                      //Set page Title
                                      this._titleService.setTitle('Contact Us');
                                      }

                                      }






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered May 8 '17 at 7:07









                                      DevnerDevner

                                      2,85164164




                                      2,85164164























                                          1














                                          In the below example:



                                          -We added object of data: { title: 'NAME' } to any routing object.



                                          -We set a basic name ("CTM") for uploading time (when clicking F5 for Refreash..): <title>CTM</title>.



                                          -We added "TitleService" class.



                                          -we handle Routher events by filtering them from app.component.ts.



                                          index.html:



                                          <!DOCTYPE html>
                                          <html>
                                          <head>
                                          <base href="/">
                                          <title>CTM</title>
                                          </head>


                                          ...



                                          app.module.ts:



                                          import { NgModule, enableProdMode } from '@angular/core';
                                          import { BrowserModule } from '@angular/platform-browser';
                                          import { TitleService } from './shared/title.service';
                                          ...


                                          @NgModule({
                                          imports: [
                                          BrowserModule,
                                          ..
                                          ],
                                          declarations: [
                                          AppComponent,
                                          ...
                                          ],
                                          providers: [
                                          TitleService,
                                          ...
                                          ],
                                          bootstrap: [AppComponent],
                                          })
                                          export class AppModule { }

                                          enableProdMode();


                                          title.service.ts:



                                          import { Injectable } from '@angular/core';
                                          import { Title } from '@angular/platform-browser';
                                          import { ActivatedRouteSnapshot } from '@angular/router';


                                          @Injectable()
                                          export class TitleService extends Title {

                                          constructor() {
                                          super();
                                          }


                                          private recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
                                          var titleParts = <string>;
                                          if (snapshot) {
                                          if (snapshot.firstChild) {
                                          titleParts = this.recursivelyGenerateTitle(snapshot.firstChild);
                                          }

                                          if (snapshot.data['title']) {
                                          titleParts.push(snapshot.data['title']);
                                          }
                                          }

                                          return titleParts;
                                          }

                                          public CTMGenerateTitle(snapshot: ActivatedRouteSnapshot) {
                                          this.setTitle("CTM | " + this.recursivelyGenerateTitle(snapshot).join(' - '));
                                          }

                                          }


                                          app-routing.module.ts:



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

                                          import { MainComponent } from './components/main.component';

                                          import { Router, CanActivate } from '@angular/router';
                                          import { AuthGuard } from './shared/auth/auth-guard.service';
                                          import { AuthService } from './shared/auth/auth.service';


                                          export const routes: Routes = [
                                          { path: 'dashboard', component: MainComponent, canActivate: [AuthGuard], data: { title: 'Main' } },
                                          ];

                                          @NgModule({
                                          imports: [
                                          RouterModule.forRoot(routes, { useHash: true }) // .../#/crisis-center/
                                          ],
                                          exports: [RouterModule],
                                          providers: [
                                          ..
                                          ]
                                          })

                                          export class AppRoutingModule { }

                                          export const componentsOfAppRoutingModule = [MainComponent];


                                          app.component.ts:



                                          import { Component } from '@angular/core';
                                          import { Router, NavigationEnd, ActivatedRouteSnapshot } from '@angular/router';
                                          import { TitleService } from './shared/title.service';

                                          @Component({
                                          selector: 'ctm-app',
                                          template: `
                                          <!--<a [routerLink]="['/dashboard']">Dashboard</a>
                                          <a [routerLink]="['/login']">Login</a>
                                          <a [routerLink]="['/']">Rooting</a>-->
                                          <router-outlet></router-outlet>
                                          `
                                          })
                                          export class AppComponent {

                                          constructor(private router: Router, private titleService: TitleService) {

                                          this.router.events.filter((event) => event instanceof NavigationEnd).subscribe((event) => {
                                          console.log("AppComponent.constructor: Setting HTML document's Title");
                                          this.titleService.CTMGenerateTitle(this.router.routerState.snapshot.root);
                                          });

                                          }


                                          }





                                          share|improve this answer






























                                            1














                                            In the below example:



                                            -We added object of data: { title: 'NAME' } to any routing object.



                                            -We set a basic name ("CTM") for uploading time (when clicking F5 for Refreash..): <title>CTM</title>.



                                            -We added "TitleService" class.



                                            -we handle Routher events by filtering them from app.component.ts.



                                            index.html:



                                            <!DOCTYPE html>
                                            <html>
                                            <head>
                                            <base href="/">
                                            <title>CTM</title>
                                            </head>


                                            ...



                                            app.module.ts:



                                            import { NgModule, enableProdMode } from '@angular/core';
                                            import { BrowserModule } from '@angular/platform-browser';
                                            import { TitleService } from './shared/title.service';
                                            ...


                                            @NgModule({
                                            imports: [
                                            BrowserModule,
                                            ..
                                            ],
                                            declarations: [
                                            AppComponent,
                                            ...
                                            ],
                                            providers: [
                                            TitleService,
                                            ...
                                            ],
                                            bootstrap: [AppComponent],
                                            })
                                            export class AppModule { }

                                            enableProdMode();


                                            title.service.ts:



                                            import { Injectable } from '@angular/core';
                                            import { Title } from '@angular/platform-browser';
                                            import { ActivatedRouteSnapshot } from '@angular/router';


                                            @Injectable()
                                            export class TitleService extends Title {

                                            constructor() {
                                            super();
                                            }


                                            private recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
                                            var titleParts = <string>;
                                            if (snapshot) {
                                            if (snapshot.firstChild) {
                                            titleParts = this.recursivelyGenerateTitle(snapshot.firstChild);
                                            }

                                            if (snapshot.data['title']) {
                                            titleParts.push(snapshot.data['title']);
                                            }
                                            }

                                            return titleParts;
                                            }

                                            public CTMGenerateTitle(snapshot: ActivatedRouteSnapshot) {
                                            this.setTitle("CTM | " + this.recursivelyGenerateTitle(snapshot).join(' - '));
                                            }

                                            }


                                            app-routing.module.ts:



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

                                            import { MainComponent } from './components/main.component';

                                            import { Router, CanActivate } from '@angular/router';
                                            import { AuthGuard } from './shared/auth/auth-guard.service';
                                            import { AuthService } from './shared/auth/auth.service';


                                            export const routes: Routes = [
                                            { path: 'dashboard', component: MainComponent, canActivate: [AuthGuard], data: { title: 'Main' } },
                                            ];

                                            @NgModule({
                                            imports: [
                                            RouterModule.forRoot(routes, { useHash: true }) // .../#/crisis-center/
                                            ],
                                            exports: [RouterModule],
                                            providers: [
                                            ..
                                            ]
                                            })

                                            export class AppRoutingModule { }

                                            export const componentsOfAppRoutingModule = [MainComponent];


                                            app.component.ts:



                                            import { Component } from '@angular/core';
                                            import { Router, NavigationEnd, ActivatedRouteSnapshot } from '@angular/router';
                                            import { TitleService } from './shared/title.service';

                                            @Component({
                                            selector: 'ctm-app',
                                            template: `
                                            <!--<a [routerLink]="['/dashboard']">Dashboard</a>
                                            <a [routerLink]="['/login']">Login</a>
                                            <a [routerLink]="['/']">Rooting</a>-->
                                            <router-outlet></router-outlet>
                                            `
                                            })
                                            export class AppComponent {

                                            constructor(private router: Router, private titleService: TitleService) {

                                            this.router.events.filter((event) => event instanceof NavigationEnd).subscribe((event) => {
                                            console.log("AppComponent.constructor: Setting HTML document's Title");
                                            this.titleService.CTMGenerateTitle(this.router.routerState.snapshot.root);
                                            });

                                            }


                                            }





                                            share|improve this answer




























                                              1












                                              1








                                              1







                                              In the below example:



                                              -We added object of data: { title: 'NAME' } to any routing object.



                                              -We set a basic name ("CTM") for uploading time (when clicking F5 for Refreash..): <title>CTM</title>.



                                              -We added "TitleService" class.



                                              -we handle Routher events by filtering them from app.component.ts.



                                              index.html:



                                              <!DOCTYPE html>
                                              <html>
                                              <head>
                                              <base href="/">
                                              <title>CTM</title>
                                              </head>


                                              ...



                                              app.module.ts:



                                              import { NgModule, enableProdMode } from '@angular/core';
                                              import { BrowserModule } from '@angular/platform-browser';
                                              import { TitleService } from './shared/title.service';
                                              ...


                                              @NgModule({
                                              imports: [
                                              BrowserModule,
                                              ..
                                              ],
                                              declarations: [
                                              AppComponent,
                                              ...
                                              ],
                                              providers: [
                                              TitleService,
                                              ...
                                              ],
                                              bootstrap: [AppComponent],
                                              })
                                              export class AppModule { }

                                              enableProdMode();


                                              title.service.ts:



                                              import { Injectable } from '@angular/core';
                                              import { Title } from '@angular/platform-browser';
                                              import { ActivatedRouteSnapshot } from '@angular/router';


                                              @Injectable()
                                              export class TitleService extends Title {

                                              constructor() {
                                              super();
                                              }


                                              private recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
                                              var titleParts = <string>;
                                              if (snapshot) {
                                              if (snapshot.firstChild) {
                                              titleParts = this.recursivelyGenerateTitle(snapshot.firstChild);
                                              }

                                              if (snapshot.data['title']) {
                                              titleParts.push(snapshot.data['title']);
                                              }
                                              }

                                              return titleParts;
                                              }

                                              public CTMGenerateTitle(snapshot: ActivatedRouteSnapshot) {
                                              this.setTitle("CTM | " + this.recursivelyGenerateTitle(snapshot).join(' - '));
                                              }

                                              }


                                              app-routing.module.ts:



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

                                              import { MainComponent } from './components/main.component';

                                              import { Router, CanActivate } from '@angular/router';
                                              import { AuthGuard } from './shared/auth/auth-guard.service';
                                              import { AuthService } from './shared/auth/auth.service';


                                              export const routes: Routes = [
                                              { path: 'dashboard', component: MainComponent, canActivate: [AuthGuard], data: { title: 'Main' } },
                                              ];

                                              @NgModule({
                                              imports: [
                                              RouterModule.forRoot(routes, { useHash: true }) // .../#/crisis-center/
                                              ],
                                              exports: [RouterModule],
                                              providers: [
                                              ..
                                              ]
                                              })

                                              export class AppRoutingModule { }

                                              export const componentsOfAppRoutingModule = [MainComponent];


                                              app.component.ts:



                                              import { Component } from '@angular/core';
                                              import { Router, NavigationEnd, ActivatedRouteSnapshot } from '@angular/router';
                                              import { TitleService } from './shared/title.service';

                                              @Component({
                                              selector: 'ctm-app',
                                              template: `
                                              <!--<a [routerLink]="['/dashboard']">Dashboard</a>
                                              <a [routerLink]="['/login']">Login</a>
                                              <a [routerLink]="['/']">Rooting</a>-->
                                              <router-outlet></router-outlet>
                                              `
                                              })
                                              export class AppComponent {

                                              constructor(private router: Router, private titleService: TitleService) {

                                              this.router.events.filter((event) => event instanceof NavigationEnd).subscribe((event) => {
                                              console.log("AppComponent.constructor: Setting HTML document's Title");
                                              this.titleService.CTMGenerateTitle(this.router.routerState.snapshot.root);
                                              });

                                              }


                                              }





                                              share|improve this answer















                                              In the below example:



                                              -We added object of data: { title: 'NAME' } to any routing object.



                                              -We set a basic name ("CTM") for uploading time (when clicking F5 for Refreash..): <title>CTM</title>.



                                              -We added "TitleService" class.



                                              -we handle Routher events by filtering them from app.component.ts.



                                              index.html:



                                              <!DOCTYPE html>
                                              <html>
                                              <head>
                                              <base href="/">
                                              <title>CTM</title>
                                              </head>


                                              ...



                                              app.module.ts:



                                              import { NgModule, enableProdMode } from '@angular/core';
                                              import { BrowserModule } from '@angular/platform-browser';
                                              import { TitleService } from './shared/title.service';
                                              ...


                                              @NgModule({
                                              imports: [
                                              BrowserModule,
                                              ..
                                              ],
                                              declarations: [
                                              AppComponent,
                                              ...
                                              ],
                                              providers: [
                                              TitleService,
                                              ...
                                              ],
                                              bootstrap: [AppComponent],
                                              })
                                              export class AppModule { }

                                              enableProdMode();


                                              title.service.ts:



                                              import { Injectable } from '@angular/core';
                                              import { Title } from '@angular/platform-browser';
                                              import { ActivatedRouteSnapshot } from '@angular/router';


                                              @Injectable()
                                              export class TitleService extends Title {

                                              constructor() {
                                              super();
                                              }


                                              private recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
                                              var titleParts = <string>;
                                              if (snapshot) {
                                              if (snapshot.firstChild) {
                                              titleParts = this.recursivelyGenerateTitle(snapshot.firstChild);
                                              }

                                              if (snapshot.data['title']) {
                                              titleParts.push(snapshot.data['title']);
                                              }
                                              }

                                              return titleParts;
                                              }

                                              public CTMGenerateTitle(snapshot: ActivatedRouteSnapshot) {
                                              this.setTitle("CTM | " + this.recursivelyGenerateTitle(snapshot).join(' - '));
                                              }

                                              }


                                              app-routing.module.ts:



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

                                              import { MainComponent } from './components/main.component';

                                              import { Router, CanActivate } from '@angular/router';
                                              import { AuthGuard } from './shared/auth/auth-guard.service';
                                              import { AuthService } from './shared/auth/auth.service';


                                              export const routes: Routes = [
                                              { path: 'dashboard', component: MainComponent, canActivate: [AuthGuard], data: { title: 'Main' } },
                                              ];

                                              @NgModule({
                                              imports: [
                                              RouterModule.forRoot(routes, { useHash: true }) // .../#/crisis-center/
                                              ],
                                              exports: [RouterModule],
                                              providers: [
                                              ..
                                              ]
                                              })

                                              export class AppRoutingModule { }

                                              export const componentsOfAppRoutingModule = [MainComponent];


                                              app.component.ts:



                                              import { Component } from '@angular/core';
                                              import { Router, NavigationEnd, ActivatedRouteSnapshot } from '@angular/router';
                                              import { TitleService } from './shared/title.service';

                                              @Component({
                                              selector: 'ctm-app',
                                              template: `
                                              <!--<a [routerLink]="['/dashboard']">Dashboard</a>
                                              <a [routerLink]="['/login']">Login</a>
                                              <a [routerLink]="['/']">Rooting</a>-->
                                              <router-outlet></router-outlet>
                                              `
                                              })
                                              export class AppComponent {

                                              constructor(private router: Router, private titleService: TitleService) {

                                              this.router.events.filter((event) => event instanceof NavigationEnd).subscribe((event) => {
                                              console.log("AppComponent.constructor: Setting HTML document's Title");
                                              this.titleService.CTMGenerateTitle(this.router.routerState.snapshot.root);
                                              });

                                              }


                                              }






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Sep 13 '17 at 8:32

























                                              answered Jun 12 '17 at 9:58









                                              DudiDudi

                                              2,31511822




                                              2,31511822























                                                  1














                                                  Angular 6+
                                                  I have modify the old code using new Pipe() and its working fine.



                                                  import { Title } from '@angular/platform-browser';
                                                  import { filter, map, mergeMap } from 'rxjs/operators';


                                                  ...



                                                  constructor(
                                                  private router: Router,
                                                  public activatedRoute: ActivatedRoute,
                                                  public titleService: Title,
                                                  ) {
                                                  this.setTitle();
                                                  }


                                                  ....



                                                  setTitle() {
                                                  this.router.events.pipe(
                                                  filter((event) => event instanceof NavigationEnd),
                                                  map(() => this.activatedRoute),
                                                  map((route: any) => {
                                                  while (route.firstChild) route = route.firstChild;
                                                  return route;
                                                  }),
                                                  filter((route) => route.outlet === 'primary'),
                                                  mergeMap((route: any) => route.data)).subscribe((event) => {
                                                  this.titleService.setTitle(event['title']);
                                                  console.log('Page Title', event['title']);
                                                  })
                                                  }





                                                  share|improve this answer






























                                                    1














                                                    Angular 6+
                                                    I have modify the old code using new Pipe() and its working fine.



                                                    import { Title } from '@angular/platform-browser';
                                                    import { filter, map, mergeMap } from 'rxjs/operators';


                                                    ...



                                                    constructor(
                                                    private router: Router,
                                                    public activatedRoute: ActivatedRoute,
                                                    public titleService: Title,
                                                    ) {
                                                    this.setTitle();
                                                    }


                                                    ....



                                                    setTitle() {
                                                    this.router.events.pipe(
                                                    filter((event) => event instanceof NavigationEnd),
                                                    map(() => this.activatedRoute),
                                                    map((route: any) => {
                                                    while (route.firstChild) route = route.firstChild;
                                                    return route;
                                                    }),
                                                    filter((route) => route.outlet === 'primary'),
                                                    mergeMap((route: any) => route.data)).subscribe((event) => {
                                                    this.titleService.setTitle(event['title']);
                                                    console.log('Page Title', event['title']);
                                                    })
                                                    }





                                                    share|improve this answer




























                                                      1












                                                      1








                                                      1







                                                      Angular 6+
                                                      I have modify the old code using new Pipe() and its working fine.



                                                      import { Title } from '@angular/platform-browser';
                                                      import { filter, map, mergeMap } from 'rxjs/operators';


                                                      ...



                                                      constructor(
                                                      private router: Router,
                                                      public activatedRoute: ActivatedRoute,
                                                      public titleService: Title,
                                                      ) {
                                                      this.setTitle();
                                                      }


                                                      ....



                                                      setTitle() {
                                                      this.router.events.pipe(
                                                      filter((event) => event instanceof NavigationEnd),
                                                      map(() => this.activatedRoute),
                                                      map((route: any) => {
                                                      while (route.firstChild) route = route.firstChild;
                                                      return route;
                                                      }),
                                                      filter((route) => route.outlet === 'primary'),
                                                      mergeMap((route: any) => route.data)).subscribe((event) => {
                                                      this.titleService.setTitle(event['title']);
                                                      console.log('Page Title', event['title']);
                                                      })
                                                      }





                                                      share|improve this answer















                                                      Angular 6+
                                                      I have modify the old code using new Pipe() and its working fine.



                                                      import { Title } from '@angular/platform-browser';
                                                      import { filter, map, mergeMap } from 'rxjs/operators';


                                                      ...



                                                      constructor(
                                                      private router: Router,
                                                      public activatedRoute: ActivatedRoute,
                                                      public titleService: Title,
                                                      ) {
                                                      this.setTitle();
                                                      }


                                                      ....



                                                      setTitle() {
                                                      this.router.events.pipe(
                                                      filter((event) => event instanceof NavigationEnd),
                                                      map(() => this.activatedRoute),
                                                      map((route: any) => {
                                                      while (route.firstChild) route = route.firstChild;
                                                      return route;
                                                      }),
                                                      filter((route) => route.outlet === 'primary'),
                                                      mergeMap((route: any) => route.data)).subscribe((event) => {
                                                      this.titleService.setTitle(event['title']);
                                                      console.log('Page Title', event['title']);
                                                      })
                                                      }






                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Jun 6 '18 at 4:22

























                                                      answered Jun 4 '18 at 9:34









                                                      Suhel KhanSuhel Khan

                                                      441315




                                                      441315























                                                          0














                                                          I can also recommend @ngx-meta/core plugin plugin that I've just released, in the case if you're looking for a method to set page title and meta tags dynamically.






                                                          share|improve this answer






























                                                            0














                                                            I can also recommend @ngx-meta/core plugin plugin that I've just released, in the case if you're looking for a method to set page title and meta tags dynamically.






                                                            share|improve this answer




























                                                              0












                                                              0








                                                              0







                                                              I can also recommend @ngx-meta/core plugin plugin that I've just released, in the case if you're looking for a method to set page title and meta tags dynamically.






                                                              share|improve this answer















                                                              I can also recommend @ngx-meta/core plugin plugin that I've just released, in the case if you're looking for a method to set page title and meta tags dynamically.







                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited Apr 22 '17 at 9:09

























                                                              answered Nov 11 '16 at 8:48









                                                              Burak TasciBurak Tasci

                                                              638917




                                                              638917























                                                                  0














                                                                  Angular 6+



                                                                  if route configured as follow :-



                                                                  Routes = [
                                                                  { path: 'dashboard',
                                                                  component: DashboardComponent,
                                                                  data: {title: 'Dashboard'}
                                                                  }]


                                                                  **Then in component constructor title can be set as follow :- **



                                                                   constructor( private _titleService: Title, public activatedRoute: ActivatedRoute) {
                                                                  activatedRoute.data.pipe(map(data => data.title)).subscribe(x => this._titleService.setTitle(x));
                                                                  }





                                                                  share|improve this answer




























                                                                    0














                                                                    Angular 6+



                                                                    if route configured as follow :-



                                                                    Routes = [
                                                                    { path: 'dashboard',
                                                                    component: DashboardComponent,
                                                                    data: {title: 'Dashboard'}
                                                                    }]


                                                                    **Then in component constructor title can be set as follow :- **



                                                                     constructor( private _titleService: Title, public activatedRoute: ActivatedRoute) {
                                                                    activatedRoute.data.pipe(map(data => data.title)).subscribe(x => this._titleService.setTitle(x));
                                                                    }





                                                                    share|improve this answer


























                                                                      0












                                                                      0








                                                                      0







                                                                      Angular 6+



                                                                      if route configured as follow :-



                                                                      Routes = [
                                                                      { path: 'dashboard',
                                                                      component: DashboardComponent,
                                                                      data: {title: 'Dashboard'}
                                                                      }]


                                                                      **Then in component constructor title can be set as follow :- **



                                                                       constructor( private _titleService: Title, public activatedRoute: ActivatedRoute) {
                                                                      activatedRoute.data.pipe(map(data => data.title)).subscribe(x => this._titleService.setTitle(x));
                                                                      }





                                                                      share|improve this answer













                                                                      Angular 6+



                                                                      if route configured as follow :-



                                                                      Routes = [
                                                                      { path: 'dashboard',
                                                                      component: DashboardComponent,
                                                                      data: {title: 'Dashboard'}
                                                                      }]


                                                                      **Then in component constructor title can be set as follow :- **



                                                                       constructor( private _titleService: Title, public activatedRoute: ActivatedRoute) {
                                                                      activatedRoute.data.pipe(map(data => data.title)).subscribe(x => this._titleService.setTitle(x));
                                                                      }






                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered Jun 25 '18 at 11:30









                                                                      Ajitesh SinhaAjitesh Sinha

                                                                      1




                                                                      1























                                                                          0














                                                                          Working fine in Angular 6 and 6+ with Pipe and map method instead of using filter



                                                                          Step1: routing setup



                                                                          {path: 'dashboard', component: DashboardComponent, data: {title: 'My Dashboard'}},
                                                                          {path: 'aboutUs', component: AboutUsComponent, data: {title: 'About Us'}},
                                                                          {path: 'contactUs', component: ContactUsComponent, data: {title: 'Contact Us Page'}},


                                                                          step2: in your app.module.ts import module



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


                                                                          then in provider add providers: [title]



                                                                          Step 3
                                                                          In your main component import



                                                                          import { Title } from "@angular/platform-browser";
                                                                          import { RouterModule, ActivatedRoute, Router, NavigationEnd } from "@angular/router";
                                                                          import { filter, map } from 'rxjs/operators';

                                                                          constructor(private titleService: Title, private router: Router, private activatedRoute: ActivatedRoute) {

                                                                          }

                                                                          ngOnInit() {

                                                                          this.router.events.pipe(map(() => {
                                                                          let child = this.activatedRoute.firstChild;
                                                                          while (child) {
                                                                          if (child.firstChild) {
                                                                          child = child.firstChild;
                                                                          } else if (child.snapshot.data && child.snapshot.data['title']) {
                                                                          return child.snapshot.data['title'];
                                                                          } else {
                                                                          return null;
                                                                          }
                                                                          }
                                                                          return null;
                                                                          })).subscribe(title => {
                                                                          this.titleService.setTitle(title);
                                                                          });

                                                                          }





                                                                          share|improve this answer






























                                                                            0














                                                                            Working fine in Angular 6 and 6+ with Pipe and map method instead of using filter



                                                                            Step1: routing setup



                                                                            {path: 'dashboard', component: DashboardComponent, data: {title: 'My Dashboard'}},
                                                                            {path: 'aboutUs', component: AboutUsComponent, data: {title: 'About Us'}},
                                                                            {path: 'contactUs', component: ContactUsComponent, data: {title: 'Contact Us Page'}},


                                                                            step2: in your app.module.ts import module



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


                                                                            then in provider add providers: [title]



                                                                            Step 3
                                                                            In your main component import



                                                                            import { Title } from "@angular/platform-browser";
                                                                            import { RouterModule, ActivatedRoute, Router, NavigationEnd } from "@angular/router";
                                                                            import { filter, map } from 'rxjs/operators';

                                                                            constructor(private titleService: Title, private router: Router, private activatedRoute: ActivatedRoute) {

                                                                            }

                                                                            ngOnInit() {

                                                                            this.router.events.pipe(map(() => {
                                                                            let child = this.activatedRoute.firstChild;
                                                                            while (child) {
                                                                            if (child.firstChild) {
                                                                            child = child.firstChild;
                                                                            } else if (child.snapshot.data && child.snapshot.data['title']) {
                                                                            return child.snapshot.data['title'];
                                                                            } else {
                                                                            return null;
                                                                            }
                                                                            }
                                                                            return null;
                                                                            })).subscribe(title => {
                                                                            this.titleService.setTitle(title);
                                                                            });

                                                                            }





                                                                            share|improve this answer




























                                                                              0












                                                                              0








                                                                              0







                                                                              Working fine in Angular 6 and 6+ with Pipe and map method instead of using filter



                                                                              Step1: routing setup



                                                                              {path: 'dashboard', component: DashboardComponent, data: {title: 'My Dashboard'}},
                                                                              {path: 'aboutUs', component: AboutUsComponent, data: {title: 'About Us'}},
                                                                              {path: 'contactUs', component: ContactUsComponent, data: {title: 'Contact Us Page'}},


                                                                              step2: in your app.module.ts import module



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


                                                                              then in provider add providers: [title]



                                                                              Step 3
                                                                              In your main component import



                                                                              import { Title } from "@angular/platform-browser";
                                                                              import { RouterModule, ActivatedRoute, Router, NavigationEnd } from "@angular/router";
                                                                              import { filter, map } from 'rxjs/operators';

                                                                              constructor(private titleService: Title, private router: Router, private activatedRoute: ActivatedRoute) {

                                                                              }

                                                                              ngOnInit() {

                                                                              this.router.events.pipe(map(() => {
                                                                              let child = this.activatedRoute.firstChild;
                                                                              while (child) {
                                                                              if (child.firstChild) {
                                                                              child = child.firstChild;
                                                                              } else if (child.snapshot.data && child.snapshot.data['title']) {
                                                                              return child.snapshot.data['title'];
                                                                              } else {
                                                                              return null;
                                                                              }
                                                                              }
                                                                              return null;
                                                                              })).subscribe(title => {
                                                                              this.titleService.setTitle(title);
                                                                              });

                                                                              }





                                                                              share|improve this answer















                                                                              Working fine in Angular 6 and 6+ with Pipe and map method instead of using filter



                                                                              Step1: routing setup



                                                                              {path: 'dashboard', component: DashboardComponent, data: {title: 'My Dashboard'}},
                                                                              {path: 'aboutUs', component: AboutUsComponent, data: {title: 'About Us'}},
                                                                              {path: 'contactUs', component: ContactUsComponent, data: {title: 'Contact Us Page'}},


                                                                              step2: in your app.module.ts import module



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


                                                                              then in provider add providers: [title]



                                                                              Step 3
                                                                              In your main component import



                                                                              import { Title } from "@angular/platform-browser";
                                                                              import { RouterModule, ActivatedRoute, Router, NavigationEnd } from "@angular/router";
                                                                              import { filter, map } from 'rxjs/operators';

                                                                              constructor(private titleService: Title, private router: Router, private activatedRoute: ActivatedRoute) {

                                                                              }

                                                                              ngOnInit() {

                                                                              this.router.events.pipe(map(() => {
                                                                              let child = this.activatedRoute.firstChild;
                                                                              while (child) {
                                                                              if (child.firstChild) {
                                                                              child = child.firstChild;
                                                                              } else if (child.snapshot.data && child.snapshot.data['title']) {
                                                                              return child.snapshot.data['title'];
                                                                              } else {
                                                                              return null;
                                                                              }
                                                                              }
                                                                              return null;
                                                                              })).subscribe(title => {
                                                                              this.titleService.setTitle(title);
                                                                              });

                                                                              }






                                                                              share|improve this answer














                                                                              share|improve this answer



                                                                              share|improve this answer








                                                                              edited Jan 4 at 6:24









                                                                              prashant rana

                                                                              1,167920




                                                                              1,167920










                                                                              answered Jan 4 at 5:33









                                                                              MujahidMujahid

                                                                              395




                                                                              395






























                                                                                  draft saved

                                                                                  draft discarded




















































                                                                                  Thanks for contributing an answer to Stack Overflow!


                                                                                  • Please be sure to answer the question. Provide details and share your research!

                                                                                  But avoid



                                                                                  • Asking for help, clarification, or responding to other answers.

                                                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                                                  To learn more, see our tips on writing great answers.




                                                                                  draft saved


                                                                                  draft discarded














                                                                                  StackExchange.ready(
                                                                                  function () {
                                                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34602806%2fhow-to-change-page-title-in-angular2-router%23new-answer', 'question_page');
                                                                                  }
                                                                                  );

                                                                                  Post as a guest















                                                                                  Required, but never shown





















































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown

































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown







                                                                                  Popular posts from this blog

                                                                                  Monofisismo

                                                                                  Angular Downloading a file using contenturl with Basic Authentication

                                                                                  Olmecas