我希望在单击按钮时动态更新徽章值。
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/