Reputation: 2025
I have problem with Ionic 2 not updating my UI when I change a variable.
html:
<ion-card *ngFor="let event of mEvents (click)="onEventCardClick(event)">
<ion-card-content ion-item>
<span class="eventTitle">{{ event.title }}</span> <br/>
<span class="relativeDate">{{ event.getRelativeTimeString() }}</span>
<ion-badge item-end>{{ event.reservationsCount }}</ion-badge>
<ion-badge *ngIf="event.hasUnreadMessages" color="danger" item-end>{{ event.unreadMessagesCount }}</ion-badge>
</ion-card-content>
</ion-card>
end from ts file:
this.fcm.onNotification().subscribe((notification:NotificationData) => {
if(!this.navCtrl.isActive(this.viewCtrl))
return;
notification.event = JSON.parse(notification.event);
notification.reservation = JSON.parse(notification.reservation);
notification.reservation_message = JSON.parse(notification.reservation_message);
let eventId: number = notification.event.id;
for(let i=0; i<this.mEvents.length; i++) {
if(this.mEvents[i].id == eventId) {
this.mEvents[i].unreadMessagesCount++;
this.mEvents[i].hasUnreadMessages = true;
return;
}
}
});
The problem is, I send a push notification from my server. i receive message successfully and update corresponding object (Event). But this last ion-badge
element in ion-card
does not shows up. It is still "hidden". However if I interact with UI, it suddenly shows up.
How can I achieve instant UI update? I read in some articles about NgZone but half of them says that is should not be used and the other half says that I should use it ...
Upvotes: 1
Views: 1387
Reputation: 2643
Use the ChangeDetectorRef. It detects changes in variables and updates the UI. Create the private ref:ChangeDetectorRef
in the constructor then call this.ref.detectChanges()
whenever you need to update the UI when your variable changes.
Upvotes: 5