Search code examples
javascriptangulartypescripttransloco

Transloco Language Switch Works but Pipe Doesn't Update URL in Angular


I'm using the @jsverse/transloco library in my Angular application to manage language translation. When I switch languages using a button, the translations are updated correctly in the template (for example, "en title" becomes "es title"). However, the link in my template doesn't change accordingly.

The link is constructed using a custom lang pipe that attaches the current language to the URL. Below is the code for my LangPipe and the switchLang method:

import { Component, inject, Injectable, isDevMode, Pipe } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import {
  provideTransloco,
  Translation,
  TranslocoLoader,
  TranslocoModule,
  TranslocoService,
} from '@jsverse/transloco';
import { HttpClient, provideHttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { provideRouter, RouterModule } from '@angular/router';

console.clear();

@Injectable({ providedIn: 'root' })
export class TranslocoHttpLoader implements TranslocoLoader {
  private http = inject(HttpClient);

  getTranslation(lang: string) {
    return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
  }
}

@Pipe({
  name: 'lang',
})
export class LangPipe {
  transloco = inject(TranslocoService);

  transform(value: string) {
    console.log({ value });
    return `${this.transloco.getActiveLang()}/${value}`.replace(/\/\//g, '/');
  }
}

@Component({
  selector: 'app-root',
  imports: [TranslocoModule, CommonModule, LangPipe],
  template: `
    in app!
    <ng-container *transloco="let t">
      <p>{{ t('title') }}</p>

      <button (click)="switchLang()">switch lang</button>
      <a [href]="'/products/1' | lang">goto to some link</a>
    </ng-container>
  `,
})
export class App {
  name = 'Angular';
  transloco = inject(TranslocoService);

  switchLang() {
    if (this.transloco.getActiveLang() === 'en') {
      this.transloco.setActiveLang('es');
    } else {
      this.transloco.setActiveLang('en');
    }
  }
}

bootstrapApplication(App, {
  providers: [
    provideHttpClient(),
    provideTransloco({
      config: {
        availableLangs: ['en', 'es'],
        defaultLang: 'en',
        reRenderOnLangChange: true,
        prodMode: !isDevMode(),
      },
      loader: TranslocoHttpLoader,
    }),
  ],
});
  • The language is switching successfully in the template (en becomes es), but the URL (generated by the lang pipe) does not update with the new language.
  • The pipe transforms the URL as expected, but it doesn’t seem to react to the language change when it's triggered by the switchLang method.

What I’ve tried:

  • I've verified that the language changes correctly with the transloco.getActiveLang() method.
  • I've also checked the lang pipe, and it correctly transforms the link based on the active language, but it does not update dynamically when the language is switched.

If Transloco has a better built-in way to handle this scenario and update the URL correctly based on the active language, I would happily use that approach instead of the custom pipe.

How can I ensure that the URL updates correctly when the language is switched?

stackblitz demo


Solution

  • Impure pipe fix:

    This fix makes the pipe run on every change detection cycle by setting the pipe as pure: false, which is less efficient, but lesser code. But I recommend the second approach:

    @Pipe({
      name: 'lang',
      pure: false,
    })
    export class LangPipe {
      transloco = inject(TranslocoService);
    
      transform(value: string) {
        console.log({ value });
        return `${this.transloco.getActiveLang()}/${value}`.replace(/\/\//g, '/');
      }
    }
    

    Stackblitz Demo

    Best Fix:

    I think it is due to the fact that the pipe is pure, so unless the input changes, the pipe will not update.

    Instead pass this language as an input to the pipe, so that when the inputs change the transform function is retriggered.

    @Pipe({
      name: 'lang',
    })
    export class LangPipe {
      transloco = inject(TranslocoService);
    
      transform(
        value: string,
        activeLang: string = this.transloco.getActiveLang()
      ) {
        console.log({ value });
        return `${activeLang}/${value}`.replace(/\/\//g, '/');
      }
    }
    

    Then pass the activeLanguage through a getter method:

    @Component({
      selector: 'app-root',
      imports: [TranslocoModule, CommonModule, LangPipe],
      template: `
        in app!
        <ng-container *transloco="let t">
          <p>{{ t('title') }}</p>
    
          <button (click)="switchLang()">switch lang</button>
          <a [href]="'/products/1' | lang : activeLang">goto to some link</a>
        </ng-container>
      `,
    })
    export class App {
      name = 'Angular';
      transloco = inject(TranslocoService);
    
      get activeLang() {
        return this.transloco.getActiveLang();
      }
    
      switchLang() {
        if (this.transloco.getActiveLang() === 'en') {
          this.transloco.setActiveLang('es');
        } else {
          this.transloco.setActiveLang('en');
        }
      }
    }
    

    Full Code:

    import { Component, inject, Injectable, isDevMode, Pipe } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    import {
      provideTransloco,
      Translation,
      TranslocoLoader,
      TranslocoModule,
      TranslocoService,
    } from '@jsverse/transloco';
    import { HttpClient, provideHttpClient } from '@angular/common/http';
    import { CommonModule } from '@angular/common';
    import { provideRouter, RouterModule } from '@angular/router';
    
    console.clear();
    
    @Injectable({ providedIn: 'root' })
    export class TranslocoHttpLoader implements TranslocoLoader {
      private http = inject(HttpClient);
    
      getTranslation(lang: string) {
        return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
      }
    }
    
    @Pipe({
      name: 'lang',
    })
    export class LangPipe {
      transloco = inject(TranslocoService);
    
      transform(
        value: string,
        activeLang: string = this.transloco.getActiveLang()
      ) {
        console.log({ value });
        return `${activeLang}/${value}`.replace(/\/\//g, '/');
      }
    }
    
    @Component({
      selector: 'app-root',
      imports: [TranslocoModule, CommonModule, LangPipe],
      template: `
        in app!
        <ng-container *transloco="let t">
          <p>{{ t('title') }}</p>
    
          <button (click)="switchLang()">switch lang</button>
          <a [href]="'/products/1' | lang : activeLang">goto to some link</a>
        </ng-container>
      `,
    })
    export class App {
      name = 'Angular';
      transloco = inject(TranslocoService);
    
      get activeLang() {
        return this.transloco.getActiveLang();
      }
    
      switchLang() {
        if (this.transloco.getActiveLang() === 'en') {
          this.transloco.setActiveLang('es');
        } else {
          this.transloco.setActiveLang('en');
        }
      }
    }
    
    bootstrapApplication(App, {
      providers: [
        provideHttpClient(),
        provideTransloco({
          config: {
            availableLangs: ['en', 'es'],
            defaultLang: 'en',
            // Remove this option if your application doesn't support changing language in runtime.
            reRenderOnLangChange: true,
            prodMode: !isDevMode(),
          },
          loader: TranslocoHttpLoader,
        }),
      ],
    });
    

    Stackblitz Demo