在Angular 2中,可以使用Angular的内置i18n功能来实现使用其他字符串作为参数来翻译字符串的功能。下面是一个示例解决方法:
{{}}
插值表达式来显示需要翻译的字符串。例如:{{ 'Hello, {name}' | translate: {name: 'John'} }}
TranslateService
并注入到组件的构造函数中。例如:constructor(private translateService: TranslateService) {}
translateService.instant()
方法来翻译字符串,并传入需要替换的参数。例如:this.translateService.instant('Hello, {name}', {name: 'John'})
TranslateModule
并在imports数组中添加。例如:imports: [TranslateModule.forRoot()]
TranslateService
的use()
方法来配置翻译服务。例如:translateService.use('en')
完整示例代码如下:
app.component.html:
{{ 'Hello, {name}' | translate: {name: 'John'} }}
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.css']
})
export class AppComponent {
constructor(private translateService: TranslateService) {
this.translateService.use('en');
}
}
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
请注意,上述示例中使用了ngx-translate库来实现翻译功能。您需要安装ngx-translate库,并根据您的具体需求进行配置。