要在Angular 5中实现模板之外使用翻译字符串,可以使用Angular提供的国际化(i18n)功能。以下是一个解决方案的代码示例:
app.module.ts
中导入必要的模块和服务:import { BrowserModule } from '@angular/platform-browser';
import { NgModule, LOCALE_ID, TRANSLATIONS, TRANSLATIONS_FORMAT } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{ provide: LOCALE_ID, useValue: 'en' }, // 设置默认语言(可根据需要更改)
{ provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }, // 设置翻译文件的格式(可根据需要更改)
{ provide: TRANSLATIONS, useFactory: getTranslations, deps: [HttpClient] } // 加载翻译文件
],
bootstrap: [AppComponent]
})
export class AppModule {}
// 加载翻译文件的函数
export function getTranslations(http: HttpClient) {
const locale = 'en'; // 翻译文件的语言(可根据需要更改)
const translationFile = `./assets/locale/messages.${locale}.xlf`; // 翻译文件的路径(可根据需要更改)
return http.get(translationFile, { responseType: 'text' });
}
app.component.ts
中使用TranslateService
来翻译字符串:import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
template: `
{{ 'TITLE' | translate }}
{{ 'MESSAGE' | translate }}
`
})
export class AppComponent {
constructor(private translate: TranslateService) {
this.translate.setDefaultLang('en'); // 设置默认语言(可根据需要更改)
}
}
app.component.html
中添加一个按钮,用于切换语言:
app.component.ts
中添加switchLanguage()
方法,用于切换语言:switchLanguage(language: string) {
this.translate.use(language);
}
messages.en.xlf
和messages.fr.xlf
。这些文件包含了不同语言的翻译字符串。例如,messages.en.xlf
的内容如下:
Title
Title
Welcome to my app!
Welcome to my app!
这样,你就可以在模板之外使用翻译字符串了。只需按照上述步骤配置Angular i18n功能,然后在模板中使用{{ 'KEY' | translate }}
来翻译字符串。