When building an Angular application with the ngx-translate utility, the translated text is not embedded directly in the source code (HTML file) but is injected dynamically later, which can pose challenges for SEO.
Dynamically injected content, like the translated text in an Angular app using ngx-translate, may not be visible to search engine crawlers.
To build an application with embedded translation text, you must implement a custom TranslateLoader for ngx-translate.
Create translation files
Create typescript files with translations. Place these files in the src/translations directory of your Angular project.
src/translations/en.ts
export const enTranslation = {
"HELLO": "Hello",
"WELCOME": "Welcome, {{name}}!",
}
src/translations/sk.ts
export const skTranslation = {
"HELLO": "Ahoj",
"WELCOME": "Vitaj {{name}}!",
}
Create a custom TranslateLoader
Place the custom TranlateLoder file in the src/utils directory of your Angular project.
src/utils/SynchronousTranslateLoader.ts
import { Injectable } from '@angular/core';
import { TranslateLoader } from '@ngx-translate/core';
import { Observable, of } from 'rxjs';
import { enTranslation } from '../translations/en';
import { skTranslation } from '../translations/sk';
@Injectable({
providedIn: 'root',
})
export class SynchronousTranslateLoader implements TranslateLoader {
private translations: { [key: string]: any } = {
en: enTranslation,
sk: skTranslation,
};
private defaultLanguage: string = 'en';
public getTranslation(lang: string): Observable<{ [key: string]: any }> {
// return this.translations[lang] || this.translations[this.defaultLanguage];
return of(
this.translations[lang] || this.translations[this.defaultLanguage]
);
}
}
Update config file
src/app/app,config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import {
TranslateLoader,
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import { SynchronousTranslateLoader } from './utils/SynchronousTranslateLoader';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideClientHydration(),
TranslateModule.forRoot({
defaultLanguage: 'en',
loader: {
provide: TranslateLoader,
useClass: SynchronousTranslateLoader,
},
}).providers!,
TranslateService,
provideHttpClient(),
],
};
By implementing a custom TranslateLoader for ngx-translate, you can ensure that translated text is embedded directly in your application’s build. This approach enhances SEO by making content immediately visible to search engines and improves performance by reducing the need for dynamic content injection.