Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Can I use translate with async pipe?

Tags:

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.

like image 898
ginna Avatar asked Jul 31 '18 19:07

ginna


People also ask

What kind of data can be used with async pipe?

With AsyncPipe we can use promises and observables directly in our template, without having to store the result on an intermediate property or variable.

What type of data works with async pipe in Angular?

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.

Why is async pipe impure?

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.

Why we use translate pipe in Angular?

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.


1 Answers

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)
like image 113
George Chondrompilas Avatar answered Sep 28 '22 17:09

George Chondrompilas