javascript - 在 Ionic 2 上动态更新标签徽章

标签 javascript angular typescript ionic2 ionic3

我希望在单击按钮时动态更新徽章值。

tabs.html

...
        <ion-tab [root]="tab1Root" tabTitle="Product" tabIcon="search"></ion-tab>
        <ion-tab [root]="tab2Root" tabTitle="Cart" tabIcon="cart" tabBadge="{{cartCount}}" tabBadgeStyle="danger"></ion-tab>
...

tabs.ts

export class TabsPage {
...
    cartCount = 0;

    tab1Root = ProductPage;
    tab2Root = CartPage;
...
}

product.html

<button ion-button full (click)="updateCart('add', p.id)">Buy Now</button>

product.ts

export class ProductPage {
...
    updateCart(action, id) {
        let cartCount = 1;

        let alert = this.alertCtrl.create({
            title: 'Success!',
            subTitle: 'You have added 1 product to the cart.',
            buttons: ['OK']
        });

        alert.present();
    }
...
}

正如我所想,let cartCount = 1; 什么都不做。我已经搜索了一个解决方案,但大多数都是针对 Ionic 1 或 AngularJS 的,它们对我没有任何帮助。

最佳答案

你可以使用 Ionic events为了那个原因。请看 this working plunker 。如您所见,在第一个选项卡中,我们会在徽章需要更新时发布一个事件:

import { Component } from '@angular/core';
import { Events } from 'ionic-angular';

@Component({..})
export class FirstTabPage {

  private count: number = 0;

  constructor(public events: Events) {}

  public updateTabBadge(): void {
    this.events.publish('cart:updated', ++this.count);
  }

}

然后我们在包含两个选项卡的页面中订阅该事件:

import { Component } from '@angular/core';
import { Events } from 'ionic-angular';

@Component({...})
export class FirstTabPage {

  private count: number = 0;

  constructor(public events: Events) {}

  public updateTabBadge(): void {
    this.events.publish('cart:updated', ++this.count);
  }

}

在 View 中:

<ion-header>
  <ion-navbar>
    <ion-title>Tabs</ion-title>
  </ion-navbar>
</ion-header>
<ion-tabs #myTabs>
  <ion-tab [root]="tab1Root" tabTitle="First Tab"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Second Tab" [tabBadge]="cartCount"></ion-tab>
</ion-tabs>

另请注意,应该使用属性绑定(bind)而不是字符串插值来绑定(bind)tabBadge。属性:[tabBadge]="cartCount"


更新

就像@skinny_jones在评论中提到,你也可以使用 Subjects/Observables达到相同的结果。您可以在 this blog post 中找到更多信息

关于javascript - 在 Ionic 2 上动态更新标签徽章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44929352/

相关文章:

javascript - JavaScript正则表达式用于字母数字,但不是全部数字

angular - amcharts 堆叠条形图 - 响应事件突出显示值(更改 alpha)

angular - adal-angular4 在 Angular 5 项目中抛出警告

Angular2 RxJs 可观察对象 : filter vs map?

typescript - ionic 2 无 'Access-Control-Allow-Origin' header

javascript - 我如何等待 Angular4 HttpClient 响应?

javascript - 如何在搜索功能中处理 'No Results Found'

javascript - 如何检查多个字符串变量是否不为空或为空?

javascript - 使用 let 初始化的函数在使用 this 访问时不会被替换

javascript - 日期选择器:无法绑定(bind)到 'bsValue',因为它不是 'input' 的已知属性