[英]ngx-translate translating in all children components of the module
我目前在angular 7上使用ngx-translate。我的項目正在翻譯兩種語言,英語和中文,該項目由如下所示的結構組成,A.component是父組件,B.component是子組件。
模塊A
{
componentB:{
B.component.ts
....
},
A.component.ts
A.module.ts
....
}
導出類 BComponent 實現 OnInit{
constructor(private translate: TranslateService
) {
translate.addLangs(['zh-CN', 'en']);
translate.use('zh-CN');
}
}
上面的代碼正在翻譯。
但是如果上面的代碼只加到A.component而不是B.component。 翻譯不會發生在 B.component 上。
不知道有沒有辦法把代碼加到模塊的父組件上,后面所有的子組件都可以自動翻譯,不用把代碼放到每個子組件里。
我認為您應該像文檔中所說的那樣注入app.component.ts
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {TranslateModule} from '@ngx-translate/core';
@NgModule({
imports: [
BrowserModule,
TranslateModule.forRoot()
],
bootstrap: [AppComponent]
})
export class AppModule { }
import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
@Component({
selector: 'app',
template: `
<div>{{ 'HELLO' | translate:param }}</div>
`
})
export class AppComponent {
param = {value: 'world'};
constructor(translate: TranslateService) {
// this language will be used as a fallback when a translation isn't found in the current language
translate.setDefaultLang('en');
// the lang to use, if the lang isn't available, it will use the current loader to get them
translate.use('en');
}
}
根據您的項目結構(如果組件 B 有我假設的自己的模塊),您可能需要按照文檔中所述的設置在Component B
模塊導入中添加TranslateModule
。
@NgModule({
imports: [
TranslateModule,
...
],
...
})
export class ComponentB {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.