1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Angular】ngx-translateをLazyLoadされるModuleでも使用したい

Posted at

はじめに

ngx-translate」を使って多言語化対応するとき、LazyLoadされるModuleのTemplateでtranslateを記述しても翻訳されない。その時どうしたら良いかを共有していく。

前提

ngx-translateの設定がapp.module.ts等でされていること。
参考サイト

ちなみに、app.component.tsで多言語の初期設定も書いておく

app.component.ts
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

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

    constructor(private translate: TranslateService) {
        this.translate.setDefaultLang('en');
        this.translate.use('en');
    }
}

各LazyLoadModuleにimportされるTranslateSharedLazyModuleを作成する

ポイントとしてはforChild()を記述する部分。
useFactoryの部分をnullにしているが、これはapp.module.tsと同じ多言語の設定を利用するならnullで良い。
※これをimportしたmoduleがロードされるたびにインスタンスが生成されるため。と言っても最初の初回のロードのみ。

src/shared/translate-shared-lazy.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';

@NgModule({
    declarations: [],
    imports: [
        CommonModule,
        TranslateModule.forChild({
            loader: {
                provide: TranslateLoader,
                useFactory: null,
            },
            isolate: false,
        }),
    ],
    exports: [TranslateModule],
})
export class TranslateSharedLazyModule {}

あとはこれをtranslateしたいModuleでimportしてやればいい。

example-lazy.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { TranslateSharedLazyModule } from '../../shared/translate-shared-lazy.module';

@NgModule({
    declarations: [],
    imports: [CommonModule, TranslateSharedLazyModule],
})
export class ExampleLazyModule {}

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?