ngx-translate / core

The internationalization (i18n) library for Angular
MIT License
4.53k stars 578 forks source link

Support for Angular v18 #1481

Closed MarikaKonturova closed 2 months ago

MarikaKonturova commented 5 months ago

In a search for solution for angular project with standalone components i find this kind of solution. I hope it will help you.

This works for angular 18 (^18.0.4)

app.config.ts

import {
  ApplicationConfig,
  importProvidersFrom,
  provideZoneChangeDetection,
} from '@angular/core';
import { provideRouter } from '@angular/router';

import {
  HttpClient,
  provideHttpClient
} from '@angular/common/http';
import { provideClientHydration } from '@angular/platform-browser';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { routes } from './app.routes';

function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
export const provideTranslation = () => ({
  loader: {
    provide: TranslateLoader,
    useFactory: HttpLoaderFactory,
    deps: [HttpClient],
  },
});

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideHttpClient(),
    importProvidersFrom([TranslateModule.forRoot(provideTranslation())]),
    provideRouter(routes),
    provideClientHydration(),
  ],
};

app.component.ts

import { ChangeDetectionStrategy, Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { MainComponent } from 'components/main/main.component';
import { SpacebgComponent } from 'components/spacebg/spacebg.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, MainComponent, SpacebgComponent, **_TranslateModule_**],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
  constructor(public translate: TranslateService) {
    translate.addLangs(['en', 'ru']);
    translate.setDefaultLang('ru');

    const browserLang = translate.getBrowserLang();
    translate.use(browserLang?.match(/en|ru/) ? browserLang : 'ru');
  }
}

app.component.html

{{ "helloworld or any other word from your json" | translate }}

maozhenhua2 commented 5 months ago

@MarikaKonturova thank you very much.

yl-endress commented 5 months ago

+1

GCancinoH commented 4 months ago

@MarikaKonturova Thank you so much! So, this library is no longer mantained?

MarikaKonturova commented 4 months ago

dunno about this library, but it seems transloco gains popularity for angular v18. still, with my config ngx-translate works too

GCancinoH commented 4 months ago

dunno about this library, but it seems transloco gains popularity for angular v18. still, with my config ngx-translate works too

Will try it; thank you so much. Checked it out transloco and didn't like the way they handle translations. This lib look easier and it's great.

cesarkohl commented 4 months ago

The last commit of this repo was in May 2023... My suggestion is to take a look at transloco.

T-Nagui commented 4 months ago

is not working in angular 18.1 :'(

yl-endress commented 4 months ago

is not working in angular 18.1 :'(

For us it's actually working in angular 18.1 in a library that is exporting the translations. This lib is still using the old module syntax:

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, "./assets/i18n/", ".json");
}

@NgModule({
  declarations: [],
  exports: [
    TranslateModule,
    ...
  ], imports: [TranslateModule.forRoot({
    loader: {
      provide: TranslateLoader,
      useFactory: createTranslateLoader,
      deps: [HttpClient]
    }
  }),
  ...,
  providers: [
    TranslateService,
    ...
  ]
})
export class MyLibModule {
}

In the final application we are just importing the lib and by this, we are also using the translation without any issue:

// appConfig.ts
export const appConfig: ApplicationConfig = {
  providers: [
    importProvidersFrom(MyLibModule),
    importProvidersFrom(OAuthModule.forRoot()),
    provideZoneChangeDetection({eventCoalescing: true}),
    provideRouter(ROUTES),
    ...
  ]
};

// main.ts
bootstrapApplication(AppComponent, appConfig)
.catch((err) => { ... });
T-Nagui commented 4 months ago

fro any one having same issue like me in angular 18.1 https://angular.dev/reference/migrations/standalone it help me to do migration to standAlone and that create a correct code of provider :

export const appConfig: ApplicationConfig = {
  providers: [
    importProvidersFrom( TranslateModule.forRoot(),...),
    ...
  ]
};

PS: for my case it was migration from angular 14 to 18 :)

yioo1217 commented 3 months ago

`X [ERROR] TS2729: Property 'translate' is used before its initialization. [plugin angular-compiler]

src/app/pages/syslog-analysis/alertRule/alertRuleDetail/alertRuleDetail.component.ts:23:19:
  23 │         true: this.translate.instant('COMMON.TRUE'),
     ╵                    ~~~~~~~~~

'translate' is declared here.

src/app/pages/syslog-analysis/alertRule/alertRuleDetail/alertRuleDetail.component.ts:35:8:
  35 │         private translate: TranslateService,
     ╵         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`

I upgraded from angular15 to 18 and found that the version I am using is reporting this error "@ngx-translate/core": "^14.0.0", "@ngx-translate/http-loader": "^8.0.0", How take this? thanks

mzeromski commented 3 months ago

Ive created solution for 18.1, you can check here https://github.com/ngx-translate/core/issues/1485

CodeAndWeb commented 2 months ago

Thanks for providing this code.

I've updated our tutorial. https://www.codeandweb.com/babeledit/tutorials/how-to-translate-your-angular-app-with-ngx-translate

I'll also update the ngx-translate documentation soon.

Majdsayedtaha commented 1 month ago

Hey there! Thanks so much for your help! I do have a quick question—wouldn't it be nice if we didn't have to import the TranslateModule every time? I was wondering if there are any other ways to make it global with the new Angular standalone versions. Appreciate any insights! @MarikaKonturova

CodeAndWeb commented 1 month ago

You can switch to my ngx-translate fork. Version 16 fully supports stand alone modules and does not require importing the module anymore. => https://ngx-translate.org/getting-started/installation/