Markel Arizaga
Markel Arizaga

Reputation: 393

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

Upvotes: 10

Views: 4967

Answers (1)

David Strahm
David Strahm

Reputation: 273

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);
    }
}

Upvotes: 16

Related Questions