I'm trying to make a custom toast notification system in Angular, but I've run into a problem. So what should happen is that I run a function on the service, which passes down a string of text, the text is pushed to the service so it can be used globally across the app and a boolean value switches to true which shows the toast and then after a timeout switches to false so it hides again. It all works right up to the point where the toast hides itself again. I did a console log on the bool value and it's switching as it should do so that's not the problem.
My toast is in it's own component and it's html is as so:
<div *ngIf="badge.showToast" id="toast">
<div id="icon-wrapper">
<i class="fa fa-check"></i>
</div>
<div id="text-wrapper">
<p id="toast-title">{{badge.badgeTitle}}</p>
<p id="toast-text">{{badge.badgeEarned}}</p>
</div>
</div>
And my service is pretty straightforward:
import { Injectable } from '@angular/core';
@Injectable()
export class BadgeService {
badgeTitle: string = "You earned a Badge!";
badgeEarned: string;
showToast: boolean = false;
constructor() { }
rewardBadge(badgeEarned: string) {
this.badgeEarned = badgeEarned;
this.showToast = true;
setTimeout(function(){ this.showToast = false; console.log(this.showToast); }, 5000);
}
}
And I'm calling the function from the app.component.ts for testing:
ngOnInit() {
this.getUserProfile();
this._badge.rewardBadge("Test badge text");
}
Surely if the showToast bool has changed to false (which the console log said it did) then I thought it should hide the div layer in the other component?