Angular: Can I use translate with async pipe?
Asked Answered
Y

3

6

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.

Yesima answered 31/7, 2018 at 19:11 Comment(1)
This should work just fine. Are you saying removing either one of those makes the other one work?Lamanna
N
4

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)
Needlework answered 11/2, 2019 at 12:1 Comment(0)
F
0

I had a similar problem. In my case it was caused by a surrounding conditional:

<div *ngIf="(obs$|async)">
  {{ 'MSG' | translate:{msg: (obs$|async)} }}
</div>

When obs$ got triggered, the *ngIf rendered the inside block. The inside block then subscribed to obs$ now, but the initial event (that triggered the outside if) is gone now. On the next event, it will render it, however (if it's not empty).

In my case I could easily help myself by using a BehaviorSubject for obs$, that always starts a new stream with the last seen value. So first, the *ngIf gets triggered, the inner block subscribes, then gets triggered immediately with the same value.

You can see it on the simplified example on https://stackblitz.com/edit/angular-translatepipe, the first block is the non-working code, the second block is how I solved it. However, that trick may not be applicable in all situations.

Figone answered 7/10, 2019 at 10:10 Comment(0)
S
0

Put translate pipe after async: {{ 'foo' | async | translate }}

Somatotype answered 17/6, 2020 at 4:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.