4

<body> and <head> tag can be get in Angular component by injectingDOCUMENT, like this:

import { DOCUMENT } from '@angular/common';
import { Inject } from '@angular/core';

export class TestComponent {
  constructor(
    @Inject(DOCUMENT) private document: Document
  )

  // get <head>
  // this.document.head

  // get <body>
  // this.document.body
}

But is it possible to get <html> tag in Angular component?

3
  • 3
    And why exactly do you want that? Commented Dec 28, 2019 at 11:35
  • 2
    document.documentElement? Commented Dec 28, 2019 at 11:35
  • @SiddAjmera sometimes, class or style may be used on <html>. But add these attributes directly on <html> in the root index.html will take effect globally. Set encapsulation: ViewEncapsulation.None in specific component to ignore the shadow dom maybe a compromise way, but it will affect all the "none encapusulation" components, which I don't want either. Commented Dec 28, 2019 at 11:44

1 Answer 1

10

The documentElement references the root element which will be <html> in the browser.

https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement

@Component({..})
public class ExampleComponent {
   public constructor(@Inject(DOCUMENT) doc: Document) {
      console.log(doc.documentElement);
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You need to change your console.log to reference the injected doc instead of the global variable. Otherwise, it looks good

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.