core icon indicating copy to clipboard operation
core copied to clipboard

feat(core): add *translateContext & *translateNamespace directives

Open FortinFred opened this issue 3 years ago • 3 comments

This PR contains no breaking changes:

Extract from README.md.

7. Use translate namespace:

You can namespace your keys using the *translateNamespace structural directive

<ul *translateNamespace="'somApp.pageX.contentComponent'">
  <li translate>key1</li>
  <li translate>key2</li>
  <li translate>key3</li>
</ul>

Would translate the somApp.pageX.contentComponent.key1, somApp.pageX.contentComponent.key2 and somApp.pageX.contentComponent.key3 keys.

The namespaces directive are also stackable:

// app.component.html
<div *translateNamespace="'someApp'">
  <router-outlet></router-outlet>
</div>
// pageX.component.html
<div *translateNamespace="'pageX'">
  <content-component></content-component>
</div>
// content.component.html
<ul *translateNamespace="'contentComponent'">
  <li translate>key1</li>
  <li translate>key2</li>
  <li translate>key3</li>
</ul>

Note:

To avoid breaking changes, the translation resolution will fallback to a non namespaced key if the key isn't found in a given namespace.

8. Use translate context:

You can use the *translateContext structural directive to provide the context of all child translation to avoir to repeat the translateParams directive.

{
  "person": {
    "bio": {
      "nameColumn": "{{firstName}} {{lastName}}",
      "addressColumn": "{{address}} {{city}} {{state}}",
      "age": "{{age}} years old"
    }
  }
}
<ul *translateContext="person">
  <li translate>person.bio.nameColumn</li>
  <li translate>person.bio.addressColumn</li>
  <li translate>person.bio.age</li>
</ul>

The context are also stackable. Meaning that context from parent dom element will be inherited and merged with the current context.

Since *translateNamespace and *translateContext are structural directives and Angular limits one structural directive per element, it is possible to provide the namespace on the *translateContext directive:

<ul *translateContext="person; namespace: 'person.bio' ">
  <li translate>nameColumn</li>
  <li translate>addressColumn</li>
  <li translate>age</li>
</ul>

FortinFred avatar Jan 10 '22 19:01 FortinFred

@ocombe I would like some feedback on this feature. Thx

FortinFred avatar Apr 27 '22 00:04 FortinFred

@FortinFred translate-context.service is missing from this PR :)

maciej-pawlisz avatar Sep 22 '22 08:09 maciej-pawlisz

@FortinFred translate-context.service is missing from this PR :)

How silly of me! Just pushed it. The service extends the translate-service which might not be disirable?! Not sure. I had to make it like this to make it work in a non ngx-translate repo.

It's kind of a hack but it makes it seperated.

Let me know.

Cheers

FortinFred avatar Oct 31 '22 00:10 FortinFred