编程语言
首页 > 编程语言> > javascript – 在Ionic 2上动态更新标签徽章

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

作者:互联网

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

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();
    }
...
}

正如我所说,让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);
  }

}

在视图中:

<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>

另请注意,应使用属性绑定而不是字符串插值来绑定tabBadge属性:[tabBadge] =“cartCount”

UPDATE

就像评论中提到的@skinny_jones一样,您也可以使用Subjects / Observables来获得相同的结果.您可以在this blog post中找到更多信息

标签:javascript,angular,typescript,ionic2,ionic3
来源: https://codeday.me/bug/20190823/1699816.html