user2564121
user2564121

Reputation: 115

Angular Routing: create different language path route to the same component form navbar component

I am using ngx-translate to translate my components. I am able to change website language if the user clicks on language link inside the same component.
In angular routing module

const routes: Routes = [
  {path: '',  redirectTo: "fr/home", pathMatch: "full"},
  {path: ':languageCode/home', component: HomeComponent},
  {path: ':languageCode/employees', component: EmployeesComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Inside each component i have a link to change to other language for the same component.
for example this is my home component template html
<h1>{{'home page' | translate}}</h1>

<p *ngIf="lang === 'fr'">
    <button class="custom-button" (click)="navigate('en')">English</button>
</p>

<p *ngIf="lang === 'en'">
     <button class="custom-button" (click)="navigate('fr')">French</button>
</p>

home component ts
export class HomeComponent implements OnInit {

 
  lang;
  constructor(private translateService: TranslateService, private router: Router, private route: ActivatedRoute) {
    this.lang = this.route.snapshot.paramMap.get('languageCode');
    console.log(this.lang);
    this.translateService.setDefaultLang('fr');
    this.translateService.use(this.lang);
  }
  ngOnInit(): void {
    this.route.params.subscribe(params => {
      this.lang = params['languageCode'];

      console.log(this.lang)
      this.translateService.use(this.lang);
    
  });
  }

  navigate(languageCode: string) {
    this.router.navigate([languageCode, "home"]);
  }
}

I have to make this for each component (which is not good), So i want to put these language link in navbar component

<p *ngIf="lang === 'fr'">
    <button class="custom-button" (click)="navigate('en')">English</button>
</p>

<p *ngIf="lang === 'en'">
     <button class="custom-button" (click)="navigate('fr')">French</button>
</p>


but the problems are:
1- i can't get the activated route to get the languageCode inside navbar component.
2- how can i know the component name which i should navigate the user to.

app.component.html

<app-navbar></app-navbar>
<router-outlet></router-outlet>

Upvotes: 2

Views: 2136

Answers (1)

qqtf
qqtf

Reputation: 711

could it be that you're confusing things? The whole purpose of using ngx-translate is that you use (and therefore route) to the same component, disregarding the chosen language by the user.

How to use ngx-translate

So your routing would be something like:

const routes: Routes = [


{path: '',  redirectTo: "home", pathMatch: "full"},
  {path: ':home', component: HomeComponent},
  {path: ':employees', component: EmployeesComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

without any references to a languagecode.

You could use a languageService like this

import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { CookieService } from 'ngx-cookie-service';

@Injectable({ providedIn: 'root' })
export class LanguageService {
  public languages: string[] = ['de', 'en', 'fr', 'nl'];

  constructor(public translate: TranslateService, private cookieService: CookieService) {
    let browserLang;
    this.translate.addLangs(this.languages);
    if (this.cookieService.check('lang')) {
      browserLang = this.cookieService.get('lang');
    }
    else {
      browserLang = translate.getBrowserLang();
    }
        translate.use(browserLang.match(/de|en|fr|nl/) ? browserLang : 'nl');
  }

  public setLanguage(lang) {
      this.translate.use(lang);
  }
}

In your topbar, you could have something like this:

<div class="dropdown d-inline-block" ngbDropdown>
            <button type="button" class="btn header-item" id="page-header-user-dropdown" ngbDropdownToggle>
                <img *ngIf="flagvalue !== undefined" src="{{flagvalue}}" alt="Header Language" height="16"> <span class="ml-1">{{countryName}}</span>
                <img *ngIf="flagvalue === undefined" src="{{valueset}}" alt="Header Language" height="16">
                <span *ngIf="flagvalue === undefined" class="ml-1">English</span>
            </button>
            <div class="dropdown-menu dropdown-menu-right" ngbDropdownMenu>
                <a href="javascript:void(0);" class="dropdown-item notify-item" *ngFor="let item of listLang"
                   (click)="setLanguage(item.text, item.lang, item.flag)" [ngClass]="{'active': currentlanguage === item.lang}">
                    <img src="{{item.flag}}" alt="user-image" class="mr-1" height="12"> <span class="align-middle">{{item.text}}</span>
                </a>
            </div>
        </div>

setLanguage(text: string, lang: string, flag: string) {
        this.countryName = text;
        this.flagvalue = flag;
        this.currentlanguage = lang;}

The rest, see How to use ngx-translate.

In case your reply would be, that's not an answer on what I've asked. Well, that's because what you're asking does not fit with the library ngx-translate you want to use, or the concept of routing in a SPA for that matter.

Hope this puts you in a different direction.

Thank you for clearly documenting your question.

Plz inform if you continue to struggle.

Be well, take care and good luck.

Upvotes: 3

Related Questions