angularngx-translateangular17

Injection error (NG0203) using ngx-translate pipe in angular 17 standalone component


We want to use ngx-tanslate in our angular-17 project, where we have no modules and only standalone components.

We get the following error:

 ERROR Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at https://angular.io/errors/NG0203
at injectInjectorOnly (core.mjs:985:15)
at ɵɵinject (core.mjs:998:42)
at ɵɵdirectiveInject (core.mjs:12042:16)
at TranslatePipe_Factory (ngx-translate-core.mjs:1050:40)
at Module.ɵɵpipe (core.mjs:28466:30)
at FooterComponent_Template (footer.component.html:21:8)

The error is thrown when the translate-pipe is called in the component template. The component definition looks like this:

@Component({
  selector: 'footer',
  templateUrl: './footer.component.html',
  imports: [MatButtonModule, TranslateModule],
  standalone: true
})

The main.ts look like this:

export function createTranslateLoader(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient);
}
bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(withInterceptorsFromDi()),
    ...
    ),
    importProvidersFrom(
      BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
      ...,
      TranslateModule.forRoot({
        loader: {
          provide: TranslateLoader,
          useFactory: createTranslateLoader,
          deps: [HttpClient]
        }
      })
    ),
  ]
}).catch(err => console.log(err));

Who to fix it?

relates to: Use @ngx-translate in standalone components in Angular 17


Solution

  • The problem was that i installed ngx-tanslate with npm install @ngx-translate/core --save as described in the ngx-translate tutorial, but the --save seems to have caused this error.

    I solved the issue by adding @ngx-translate/core and ../http-loader manually to the package.json dependencies.