What would be the best way to use the translate pipe with the async pipe in an HTML template?
For example, assuming 'foo' and 'bar' had values:
{{ 'foo' | translate: '{ bar: (bar$ | async) }' }}
appears as empty after compile.
With AsyncPipe we can use promises and observables directly in our template, without having to store the result on an intermediate property or variable.
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.
Because of the way Promise s work, Angular's async pipe has to be impure (meaning that it can return different outputs without any change in input). The transform method on Pipe s is synchronous, so when an async pipe gets a Promise , the pipe adds a callback to the Promise and returns null.
The service also contains a method called translate. It is later called by the pipe to get the translation for a specific key. It always uses the language specified in the 'language'-variable of the service, to lookup the translation. That's it.
You should not add quotes to the translate
object.
<!-- Works! -->
{{ 'foo' | translate: { bar: (bar$ | async) } }}
<!-- Doesn't work -->
{{ 'foo' | translate: '{ bar: (bar$ | async) }' }}
ERROR SyntaxError: Wrong parameter in TranslatePipe. Expected a valid Object, received: { bar: (bar$ | async) }
at TranslatePipe.push../node_modules/@ngx-translate/core/fesm5/ngx-translate-core.js.TranslatePipe.transform (ngx-translate-core.js:1178)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With