Apart from the Meta
and Title
services, Angular doesn't provide a straight forward way of manipulating the <head>
element.
The HeadService
provides tools for elements lookup, adding elements and removing them from <head>
.
If you're looking for a way to lazy load a script or a style, see
LazyLoaderService
instead.
Import CoreModule
into your app:
Inject HeadService
in your components/services and call its methods as needed:
When adding elements, you can provide an element configurator. The configurator is either an object or a function.
A configurator object is an { [attribute]: value }
object. After element creation, each attribute in the object will be written to the element before it is added to the DOM.
A configurator function is a (element) => void
function. After element creation, the native element will be passed into your function so you have a chance at manipulating it before adding it to the DOM.
The findElements()
and removeElements()
methods both use the same mechanism for element lookup:
Tag name + any additional attributes you provide.
Lookup is done using AND
comparisons, meaning all provided arguments must match exactly for the element to be grabbed.
Tip Specifying the wildcard
'**'
as an attribute value will match elements with marked with the attribute, regardless of the attributes value. Example:
The service uses the DocumentRef
service internally. If you need to mock the document object or any of its children see mocking DOCUMENT.