Search code examples
angularangular-routing

Dynamic title for specific component Angular


Im using Angular 8 with Java Spring server side. Now this is my routing

{ 
  component: IndexComp
  path: "index"
},
{ 
  component: BlogComp
  path: "blog"
},
{ 
  component: ProductComp
  path: "product/:id"
},

Default title is "Shop", and used in Blog and Index page. But in Product page, the title is from server (maybe Iphone7, Iphone8, Skirt,... depend on data from server). I want to know how to change the title in Product page, tks


Solution

  • Take a look at Title from @angular/platform-browser.

    You can inject it in the component and use setTitle('You title string here')

    E.g.:

      constructor(private readonly titleService: Title) {
        const title = 'Shop'; // get title data from the server
        this.titleService.setTitle(title);
      }
    

    UPD: based on this you can make it where ever you want: in resolver/component/service etc.


    UPD: according to the route: you can make smth like that in AppComponent, for example

      constructor(private readonly titleService: Title,
                  private readonly router: Router) {
        this.router.events.subscribe(route => {
          if (route instanceof NavigationEnd && route.urlAfterRedirects !== '/product') {
            const title = 'Dynamic Title String Here';
            this.titleService.setTitle(title);
          } else {
            const title = 'Default Title String Here';
            this.titleService.setTitle(title);
          }
        });
      }