{ "id": "guide/set-document-title", "title": "Set the document title", "contents": "\n\n\n
Your app should be able to make the browser title bar say whatever you want it to say.\nThis cookbook explains how to do it.
\nSee the
The obvious approach is to bind a property of the component to the HTML <title>
like this:
Sorry but that won't work.\nThe root component of the application is an element contained within the <body>
tag.\nThe HTML <title>
is in the document <head>
, outside the body, making it inaccessible to Angular data binding.
You could grab the browser document
object and set the title manually.\nThat's dirty and undermines your chances of running the app outside of a browser someday.
Running your app outside a browser means that you can take advantage of server-side\npre-rendering for near-instant first app render times and for SEO. It means you could run from\ninside a Web Worker to improve your app's responsiveness by using multiple threads. And it\nmeans that you could run your app inside Electron.js or Windows Universal to deliver it to the desktop.
\nTitle
servicelinkFortunately, Angular bridges the gap by providing a Title
service as part of the Browser platform.\nThe Title service is a simple class that provides an API\nfor getting and setting the current HTML document title:
getTitle() : string
—Gets the title of the current HTML document.setTitle( newTitle : string )
—Sets the title of the current HTML document.You can inject the Title
service into the root AppComponent
and expose a bindable setTitle
method that calls it:
Bind that method to three anchor tags and voilà!
\nHere's the complete solution:
\nTitle
service in bootstrap
linkGenerally you want to provide application-wide services in the root application component, AppComponent
.
This cookbook recommends registering the title service during bootstrapping,\na location you reserve for configuring the runtime Angular environment.
\nThat's exactly what you're doing.\nThe Title
service is part of the Angular browser platform.\nIf you bootstrap your application into a different platform,\nyou'll have to provide a different Title
service that understands\nthe concept of a \"document title\" for that specific platform.\nIdeally, the application itself neither knows nor cares about the runtime environment.