i18n on attributes with pluralization/selection in Angular 7
Asked Answered
L

2

7

Short question

Can I have an input element where the placeholder text changes depending on the state of the component?

Longer question

Angular has the possibility to add i18n through the following syntax example:

<input i18n-placeholder placeholder="default placeholder" />

It also has the possibility to add pluralization rules through the following syntax example:

<span i18n>
    Updated {minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago}}
</span>

I've tried to merge these two features, so that the text of the placeholder changes depending on the state of the component. The component template contains the following html:

<input i18n-placeholder placeholder="Add {stuff.length, plural, =0 {} other {more}} stuff..." />

I expect the placeholder to say Add stuff... in the singular case, and Add more stuff... in the plural case, but all I get in the placeholder is Add.

Is there a way to get pluralized i18n in html attributes without copying the element and using *ngIf?

Here's a stackblitz with a working example

Laniary answered 3/7, 2019 at 11:29 Comment(0)
K
7

This doesn't actually have much to do with i18n. It only shows that Angular doesn't seem to be able to properly parse and process plural expressions inside attributes.

A (relatively dirty) workaround would be to simply put that expression inside an invisible DOM node (a template, for example), to i18n this DOM node, and to insert the text of that DOM node inside the placeholder:

<input #myInput [placeholder]="ph.innerText">

<template #ph i18n>Add {stuff.length, plural, =0 {} other {more}} stuff...</template>

Note: it's <template>, not <ng-template>!

Kristine answered 3/7, 2019 at 11:51 Comment(2)
Thank you! I actually just figured this out before I got your answer. It's not pretty, but it works for now. I hope Angular makes this easier in the futureLaniary
This solution does not work for me in Angular 14 anymore. The innerText property is empty string. Any idea how to fix it? EDIT: using <span style="display:none"> instead of <template> seems to be working, but it is stinky.Engrain
N
4

There is a solution with i18nPlural pipe.

<input placeholder="{{ stuff.length | i18nPlural : {
    '=0': 'No stuff.',
    '=1': 'One stuff.',
    'other': '# stuff.'} }}">
Nonego answered 18/5, 2020 at 23:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.