1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

TranslatePipe ngx-translate globally

Discussão em 'Angular' iniciado por Riccardo, Novembro 5, 2024 às 14:23.

  1. Riccardo

    Riccardo Guest

    I'm using angular in setup which uses app.config and ngx-translate library. I created a TranslationModule file that initializes my language throughout my application but to do the translate in each component I need to import TranslatePipe. I would like to import TranslatePipe globally so I don't need to import it into each component.

    this is translation.module.ts

    const httpLoaderFactory: (http: HttpClient) => TranslateHttpLoader = (http: HttpClient) =>
    new TranslateHttpLoader(http, './i18n/', '.json');
    export function initializeLanguage(translate: TranslateService): () => Promise<void> {
    return async () => {
    translate.addLangs(['it', 'en']);
    translate.setDefaultLang('en');
    await lastValueFrom(translate.use(translate.getBrowserLang() || "en"));
    };
    }

    @NgModule({
    imports: [
    TranslateModule,
    TranslateModule.forRoot({
    loader: {
    provide: TranslateLoader,
    useFactory: httpLoaderFactory,
    deps: [HttpClient]
    }
    }),
    ],
    providers: [
    {
    provide: APP_INITIALIZER,
    useFactory: initializeLanguage,
    deps: [TranslateService],
    multi: true,
    },
    ],
    exports: [TranslateModule]
    })
    export class TranslationModule { }


    this is app.config.ts

    export const appConfig: ApplicationConfig = {
    providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideHttpClient(),
    importProvidersFrom(TranslationModule)
    ]
    };


    this is app.component.ts (correct)

    @Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet, TranslatePipe],
    templateUrl: './app.component.html',
    styleUrl: './app.component.scss'
    })
    export class AppComponent {
    }


    this is app.component.ts (wrong)

    @Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet],
    templateUrl: './app.component.html',
    styleUrl: './app.component.scss'
    })
    export class AppComponent {
    }


    this is app.component.html

    <div>
    <h1>{{ 'app.hello' | translate }}</h1>
    </div>

    Continue reading...

Compartilhe esta Página