From 89f7e804f6160c51fd148176e5a119308f72a1e5 Mon Sep 17 00:00:00 2001 From: henriquefaria Date: Fri, 8 Jul 2022 16:34:24 +0100 Subject: [PATCH] fix(service): allow setting translations in deep objects --- .../core/src/lib/translate.service.ts | 10 +++++++++- .../core/tests/translate.service.spec.ts | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/projects/ngx-translate/core/src/lib/translate.service.ts b/projects/ngx-translate/core/src/lib/translate.service.ts index 656689d..a60b6c0 100644 --- a/projects/ngx-translate/core/src/lib/translate.service.ts +++ b/projects/ngx-translate/core/src/lib/translate.service.ts @@ -458,7 +458,15 @@ export class TranslateService { * Sets the translated value of a key, after compiling it */ public set(key: string, value: string, lang: string = this.currentLang): void { - this.translations[lang][key] = this.compiler.compile(value, lang); + const keys = key.split('.'); + const translationKey = keys.pop() as string; + const translation = keys.reduce((translation, subKey) => { + if (!translation[subKey] || typeof translation[subKey] !== 'object') { + translation[subKey] = {}; + } + return translation[subKey]; + } , this.translations[lang]); + translation[translationKey] = this.compiler.compile(value, lang); this.updateLangs(); this.onTranslationChange.emit({lang: lang, translations: this.translations[lang]}); } diff --git a/projects/ngx-translate/core/tests/translate.service.spec.ts b/projects/ngx-translate/core/tests/translate.service.spec.ts index e8c056f..9e22c6a 100644 --- a/projects/ngx-translate/core/tests/translate.service.spec.ts +++ b/projects/ngx-translate/core/tests/translate.service.spec.ts @@ -397,6 +397,21 @@ describe('TranslateService', () => { translate.set("TEST", "This is a test", 'en'); }); + it('should set a nested property in the translation value', () => { + const translation = { name: 'Name' } as any; + const defaultLang = 'en'; + translate.setTranslation(defaultLang, translation); + translate.set('profile.name', 'Profile Name', defaultLang); + expect(translation?.profile?.name).toEqual('Profile Name'); + }); + + it('should replace an existing translation ', () => { + const translation = { name: 'OldName' } as any; + translate.setTranslation('en', translation); + translate.set('name', 'New Name', 'en'); + expect(translation.name).toEqual('New Name'); + }); + it('should trigger an event when the lang changes', () => { let tr = {"TEST": "This is a test"}; translate.setTranslation('en', tr);