Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of import { DOCUMENT } from '@angular/common'; if I can already access the document

Why should we bother using import { DOCUMENT } from '@angular/common'?

Even without it I can access the document module

document.getElementById('TestID).focus()

The only difference I see with the import is having it attached to this keyword.

this._document.getElementById('TestID').focus();

Is there any real benefit to importing DOCUMENT from Angular's common module?

I did some research but cannot see any information on this.

like image 256
L1ghtk3ira Avatar asked Aug 23 '18 18:08

L1ghtk3ira


1 Answers

In our use case, the most important reason we inject the DOCUMENT instead of using it directly is for Server Side Rendering. If you call document.xxx directly in any regular lifecycle hooks like ngOnInit/ngAfterViewInit, you will mostly probably get document not defined error during SSR. Using DI to inject it could avoid this.

like image 157
LeOn - Han Li Avatar answered Sep 28 '22 08:09

LeOn - Han Li