您好,登錄后才能下訂單哦!
在Angular項目中,可以使用Angular國際化(i18n)來支持多語言。以下是配置和使用國際化的步驟:
npm install @ngx-translate/core @ngx-translate/http-loader
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
@NgModule({
declarations: [
// Your components
],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
// en.json
{
"HELLO": "Hello",
"WORLD": "World"
}
// zh.json
{
"HELLO": "你好",
"WORLD": "世界"
}
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 translate: TranslateService) {
this.translate.setDefaultLang('en');
this.translate.use('en');
}
}
<h1>{{ 'HELLO' | translate }}</h1>
<p>{{ 'WORLD' | translate }}</p>
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-language-switcher',
templateUrl: './language-switcher.component.html',
styleUrls: ['./language-switcher.component.css']
})
export class LanguageSwitcherComponent {
constructor(private translate: TranslateService) {}
switchLanguage(lang: string) {
this.translate.use(lang);
}
}
通過以上步驟,您可以在Angular項目中配置和使用國際化來支持多語言。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。