Angular 2+ dynamic translated page title using "TranslateService" & "Title"

2.8k views Asked by At

I'm trying implement multilingual possibilities in my app, and I'm using ngx-translate. Now my app has possibilities to switch language from English to Russian, and it's work fine, but I want that my app would have dynamic page title. I'm using Title service and it's work fine too, but when I switching language the title still in default language.

HOW CAN I HAVE DYNAMIC TRANSLATED TITLE IN MY APP???

~apologies for a grammatical mistakes

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';

    // i18n
    import {HttpClientModule, HttpClient} from '@angular/common/http';
    import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
    import {TranslateHttpLoader} from '@ngx-translate/http-loader';
    import { AppRoutingModule } from './app-routing.module';   
    import { AppComponent } from './app.component';

    // i18n function
    export function HttpLoaderFactory(http: HttpClient) {
      return new TranslateHttpLoader(http);
    }

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient]
          }
        }),
        AppRoutingModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

app.companent.ts

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { TranslateService } from '@ngx-translate/core';

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor (
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private titleService: Title,
    private translateService: TranslateService
  ) { }

  ngOnInit() {
    this.defaultLanguage();
    this.routerTitle();
  }

  routerTitle() {
    this.router.events
      .filter((event) => event instanceof NavigationEnd)
      .map(() => this.activatedRoute)
      .map((route) => {
        while (route.firstChild) route = route.firstChild;
        return route;
      })
      .filter((route) => route.outlet === 'primary')
      .mergeMap((route) => route.data)
      .subscribe((event) => this.titleService.setTitle(this.translateService.instant(event['title'])));
  }

  defaultLanguage() {
    this.translateService.addLangs(['tj', 'ru', 'en']);
    let lang = localStorage.getItem('language');
    if(lang !== null) {
      this.translateService.use(lang);
    }
    else {
      this.translateService.setDefaultLang('tj');
    }
  }

  switchLanguage(language: string) {
    this.translateService.use(language);
    localStorage.setItem('language', language);
  }

}
2

There are 2 answers

2
porgo On BEST ANSWER

change instant() method to stream() here:

this.titleService.setTitle(this.translateService.stream(event['title'])));
0
Yassir Khaldi On

Add these couple of lines on all your component constructors/onInit:

// For first initalization
translate.get("key").subscribe(value => this.titleService.setTitle(value));

// To subscribe to language changes in the future
translate.onLangChange.subscribe(e => {
  translate.get("key").subscribe(value => this.titleService.setTitle(value));
});