flobacca
flobacca

Reputation: 968

Angular Universal html lang tag

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.

Upvotes: 24

Views: 14960

Answers (2)

Alexander Repollo
Alexander Repollo

Reputation: 29

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.

Upvotes: 2

yurzui
yurzui

Reputation: 214007

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'; 
  }
  ...
}

Upvotes: 55

Related Questions