【问题标题】:Display "99+" if a number is greater than some value I assign如果数字大于我分配的某个值,则显示“99+”
【发布时间】:2019-07-17 08:54:32
【问题描述】:

我的通知变量有一个动态数字计数。

如果小于 99,我使用三元运算符显示该数字,否则,我想显示“99+”。

我试过这个:

<div class="notification-badge" *ngIf="unreadNotificationsCount > 0">
  {{(unreadNotificationsCount < 99) ? {{unreadNotificationsCount}} : '99+'}}

..但它不允许在三元内进行字符串插值

【问题讨论】:

  • {{(unreadNotificationsCount
  • @ritaj 您需要双括号将数据绑定到 html。您的解决方案不会被绑定/渲染,它只是一个字符串/文本。

标签: angular conditional-operator string-interpolation


【解决方案1】:

{s 太多。

{{ (unreadNotificationsCount < 99) ? unreadNotificationsCount : '99+' }}

应该可以。

【讨论】:

  • 我在轮询 {{unreadNotificationsCount }} 中需要这个变量。它会显示数据吗?
  • 外部{{ }} 已经表示“评估表达式(在每个更改检测周期)”。无需在表达式中重复。
【解决方案2】:

您不能在另一个 {{}} 中使用 {{}}

试试这个:

{{(unreadNotificationsCount < 99) ? unreadNotificationsCount : '99+'}}

【讨论】:

  • 这个成功了!非常感谢!
  • 不客气。请点赞并接受我的回答好吗?
【解决方案3】:
  1. 对于更多可重复使用的东西,您可以使用自定义管道。

你的组件.component.html

<div *ngIf="yourNumber">
    {{ yourNumber | transalateNumber }}
</div>

transalate-number.pipe.ts

@Pipe({name: 'transalateNumber'})
export class TransalateNumberPipe implements PipeTransform {
    transform(value: number): string {
        if (value <= 99) {
            return value.toString();
        } else {
            return '99+';
        }
    }
}

2。尝试在 .ts 文件中格式化您的号码。

你的组件.component.html

<div *ngIf="yourNumber">
    {{ formatNumber(yourNumber) }}
</div>

你的组件.component.ts

...
yourNumber: number = 100;

formatNumbar(value: number): string {
    if (value <= 99) {
        return value.toString();
    } else {
        return '99+'
    }
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多