Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing root html tag from an Angular 2 component

So the question is, is it possible to use the Renderer to tweak tags that are outside the main Angular 2 app component, like the tag? If yes, what is the best way to do this?

Let me give a bit of background. I'm trying to build a multilanguage site with Angular 2 and I came across a problem I could not find solution for. The thing is I am using the lang attribute in the html tag to define what language the site has at each moment, for example:

<html lang="en"> // When we have English locale active

So when the user clicks on a different language I update the site language using ng2-translate, which works perfect. The problem is that I need to update the property accordingly but I can't find the correct way of doing this in Angular 2 (if it's even possible). For now, I am directly touching the DOM but this won't work for me because I need to be abstracted from it (I'm using Universal too, so I need server side rendering to work).

For now, the styling of the app relays on this property (we support Arabic and this means changing the direction of the text if lang="ar"). I guess I could use a class on my main component or something like that, but using the lang property seems the correct approach to me. Any ideas?

Thanks

like image 310
Markel Arizaga Avatar asked Mar 06 '17 11:03

Markel Arizaga


People also ask

Where is the root element of an HTML document?

The <html> HTML element represents the root (top-level element) of an HTML document, so it is also referred to as the root element. All other elements must be descendants of this element.

Which tag is the root tag of an HTML document?

The <html> element is the root element and it defines the whole HTML document. It has a start tag <html> and an end tag </html> . The <body> element defines the document's body. It has a start tag <body> and an end tag </body> .

Does HTML have root tags?

HTML Root Tags represent the main or the starting tag that should be present in all the HTML documents. The HTML tag is the first tag that comes after the <! DOCTYPE> tag and within which other HTML tags are specified.


1 Answers

You can use the DOCUMENT DI Token from Angular to perform Dom operations:

import { Inject } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { DOCUMENT } from '@angular/common';

export class AppComponent {

    constructor(private translate: TranslateService, @Inject(DOCUMENT) private _document: any) {
        translate.onLangChange.map(x => x.lang)
            .subscribe(lang => this._document.documentElement.lang = lang);
    }
}
like image 110
David Strahm Avatar answered Oct 24 '22 17:10

David Strahm