Reputation: 9
I'm working on an Angular 17 application where I've implemented i18n for internationalization. Initially, I've set Arabic as the default language for the entire application. Now, I need to switch to English for specific components based on some condition. Could someone guide me on how to achieve this. Thank you
public sidebarShow: boolean = false;
setLang = 1; // Assuming setLang is set based on some condition
constructor(@Inject(LOCALE_ID) public locale: string,
private cdr: ChangeDetectorRef) {
}
ngOnInit(): void {
this.setLocale();
}
setLocale(): void {
if (this.setLang === 1)
{
// Set English locale
this.locale = 'en-US';
console.log(this.locale)
} else {
// Set Arabic locale
this.locale = 'ar-SA';
console.log(this.locale);
}
this.cdr.detectChanges(); // Trigger change detection
}
<div >
<div class="bg-primary" >
<h1 i18n>Features sections</h1>
<p i18n>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora excepturi, ducimus repudiandae aspernatur molestias accusantium debitis iusto praesentium voluptate error mollitia pariatur fugit qui ut deserunt quod rem magnam hic!</p>
<p i18n>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora excepturi, ducimus repudiandae aspernatur molestias accusantium debitis iusto praesentium voluptate error mollitia pariatur fugit qui ut deserunt quod rem magnam hic!</p>
<p i18n>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora excepturi, ducimus repudiandae aspernatur molestias accusantium debitis iusto praesentium voluptate error mollitia pariatur fugit qui ut deserunt quod rem magnam hic!</p>
</div>
</div>
<div>
<h1 i18n>Blogs sections</h1>
<p i18n>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora excepturi, ducimus repudiandae aspernatur molestias accusantium debitis iusto praesentium voluptate error mollitia pariatur fugit qui ut deserunt quod rem magnam hic!</p>
<p i18n>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora excepturi, ducimus repudiandae aspernatur molestias accusantium debitis iusto praesentium voluptate error mollitia pariatur fugit qui ut deserunt quod rem magnam hic!</p>
<p i18n>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora excepturi, ducimus repudiandae aspernatur molestias accusantium debitis iusto praesentium voluptate error mollitia pariatur fugit qui ut deserunt quod rem magnam hic!</p>
</div>
Upvotes: 0
Views: 318
Reputation: 1220
Switching of language for a subset of your application is not possible with Angular i18n since the translations are compiled ahead of time into the distribution bundle.
It is possible to load translations at runtime with Angular i18n but this still requires a hard reload and even with that you can´t set another language for a specific component.
To achieve this behaviour use for example transloco.
Upvotes: -1