TLDR Summary
UseDocumentRef
to safely access thedocument
object and/or mock it with a simple to use class and syntax.
The document
object is necessary many times when working with the web, and normally we would summon it directly in out code. However, document
doesn't always exist when working with angular.
Angular serves for many purposes other than web development:
Basically, this means that our application might be run in different environments, others than the normal browser, hence will not have the document
object.
DOCUMENT
token?Angular's DOCUMENT
token will actually, depending on the platform, provide the correct DOM Adapter.
Drawbacks:
@Inject(DOCUMENT)
syntax. Personally, I hate it. 😒DOCUMENT
token is used internally by angular, meaning attempts to mock and replace it directly might break your app/spec. 🤦♂️The DocumentRef
service acts as an injectable angular wrapper for the javascript document
object. By default, DocumentRef
will use angular's implementation to provide the native document, but you can always mock and provide another implementation.
This eventually gives you the ability to use the DocumentRef
service in your apps and, when needed, mock or provide a different implementation for the service, the DOCUMENT
token, or both.
CoreModule
into your app:DocumentRef
in your components and use .nativeDocument
to access the document
object:Mocking and replacing implementation