Angular Universal html lang tag
Asked Answered
N

2

24

In Angular Universal I have an index.html file. At the top it has

<html lang="en">

I would like to change this based on the page I am on. maldonadoattorney.com/es/jailreleases would be

<html lang="es">

maldonadoattorney.com/jailreleases would be

<html lang="en">

Is there an accepted way of doing this? Have read other questions and DOCUMENT is deprecated, so am wary of using it.

I have my site map set up with hreflang tags, but would like the html lang tag to be correct. Currently, I'm taking the lang="en" tag out of my index.html.

Notepaper answered 31/12, 2018 at 19:20 Comment(0)
K
54

You're right but DOCUMENT from @angular/platform-browser is deprecated in favor of DOCUMENT from @angular/common.

So you can use the following code:

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

...

export class AppComponent implements OnInit {

  constructor(@Inject(DOCUMENT) private document: Document) {}

  ngOnInit() {
    this.document.documentElement.lang = 'es'; 
  }
  ...
}
Kuenlun answered 1/1, 2019 at 13:47 Comment(1)
If you are using angular-i18n and want to change locale based on build, also do @Inject(LOCALE_ID) locale: string in the constructor to get the language code and set locale to this.document.documentElement.lang.Ewell
G
1

Update for 2023, Angular 15, the code works, but I had to add a few imports, like this:

import { Component, Inject, InjectionToken, OnInit } from '@angular/core';
import { DOCUMENT } from '@angular/common';
...
export class HomeEsComponent implements OnInit {

constructor( @Inject(DOCUMENT) private document: Document) {}

ngOnInit() {
  this.document.documentElement.lang = 'es'; 
}
}

Hope it helps somebody else who's looking for the same.

Gastongastralgia answered 6/7, 2023 at 19:58 Comment(2)
And why does it need these imports? What do they do?Wordy
@Wordy The code needs these imports to bring up all the decorators and methods needed from the different angular libraries, to manipulate the HTML attribute. Otherwise, if you execute the code without these imports, it'll show you an error saying that it couldn't find the resources or the word you typed in the code "doesn'texist". You can comment the imports and try to run the code, so you can see what I mean. Happy coding! :DGastongastralgia

© 2022 - 2024 — McMap. All rights reserved.