Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular TranslateService translate <title> tag

Using the TranslateService in Angular I want the <title> tag which sits in the index.html to be in different languages.

<title translate>application.title</title>

I translate all other html tags like that unless they are custom html tags then it's like this:

{{"document.name"|translate}}

The problem might be that index.html is in a different level in the folders

src
|-app
.... |-translation
|-index.html

like image 622
Jan De Dev Avatar asked May 23 '17 13:05

Jan De Dev


2 Answers

From the angular docs:

Title

Since an Angular application can't be bootstrapped on the entire HTML document (<html> tag) it is not possible to bind to the text property of the HTMLTitleElement elements (representing the <title> tag). Instead, this service can be used to set and get the current title value.

You just need to use the Title service in combination with TranslateService

export class SomeComponent {
  constructor(private title:Title, private translate:TranslateService){}
  ngOnInit(){
    this.translateService.get("document.name").subscribe(name=>{
      this.title.setTitle(name);
    });
  }
}

Please, also take a look at this cookbook.

like image 156
n00dl3 Avatar answered Nov 09 '22 22:11

n00dl3


I am using ngx-translate with xliffmerge to prevent overwriting existing text and automatically add new texts to the xlf file. But text is only added if it exists in a template. Therefore the accepted answer is not what I want.

Instead I have created a directive that I can use to add the title in a html element on every page. The title is now automatically translated and the directive then grabs the text and changes the title via Angulars title service.

The directive:

import { Directive, ElementRef, AfterContentInit  } from '@angular/core';
import { Title } from '@angular/platform-browser';

@Directive({
  selector: '[edHeadTitle]'
})

export class HeadTitleDirective implements AfterContentInit{

  constructor(private el: ElementRef,private titleService: Title) {}

  ngAfterContentInit(){
    this.titleService.setTitle(this.el.nativeElement.innerHTML);
  }

}

Then on any page (component) which must change the title, e.g. the page displaying terms:

<h2 edHeadTitle i18n class="headerTitle">Terms and conditions</h2>

If you don't want the title to display on the page, just set "display:none" in the headerTitle css class.

like image 26
Jette Avatar answered Nov 09 '22 22:11

Jette