admin管理员组文章数量:1278910
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
becomeses
), but the URL (generated by thelang
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
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
becomeses
), but the URL (generated by thelang
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
Share Improve this question asked Feb 25 at 9:18 JonJon 3354 silver badges11 bronze badges1 Answer
Reset to default 1Impure 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
本文标签: javascriptTransloco Language Switch Works but Pipe Doesn39t Update URL in AngularStack Overflow
版权声明:本文标题:javascript - Transloco Language Switch Works but Pipe Doesn't Update URL in Angular - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741217279a2360289.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论