在组件中添加TranslateService才能使用ngx-translate。例如,在想要使用ngx-translate的组件中,可以在组件中注入TranslateService并在构造函数中调用getTranslation方法加载翻译:
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-my-component',
template: `
{{ 'HELLO' | translate }}!
`
})
export class MyComponent {
constructor(private translate: TranslateService) {
this.translate.getTranslation('en').subscribe((res: string[]) => {
this.translate.setTranslation('en', res);
this.translate.use('en');
});
}
}
这里的'en'是指定语言的代码,可以更改为所需的语言。稍后调用setTranslation方法将获取的翻译加载到translate服务中。然后可以使用ngx-translate pipe('translate')将文本翻译为选定的语言。
确保在组件模块中添加ngx-translate模块,如下所示:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TranslateModule } from '@ngx-translate/core';
import { MyComponent } from './my.component';
@NgModule({
declarations: [MyComponent],
imports: [
CommonModule,
TranslateModule
],
exports: [MyComponent]
})
export class MyModule { }