Reputation: 621
I developed a service that allows me to activate a button and see its status in the different components. When I click start / pause, the button changes image.
In StackBlitz, the code works perfectly, but when I implement it in my project, the function only passes once in ngOnInit
and no longer loads, no longer changing the image of the buttons between the components.
Is there a way to implement this but without using ngOnInit
?
I used setinterval
and the button changes the image, but it doesn't seem the best solution.
Can anyone help me?
Problem --- component about
currentState: string;
ngOnInit() {
this.currentState = this.servicesService.getCurrentState();
}
html
<div class="container" style="margin-top: 10%">
<div class="btn-group" dropdown>
<button id="button-basic" dropdownToggle type="button" class="btn ">
<img style="width: 35px;" *ngIf="currentState=='pause'" src="https://img.icons8.com/carbon-copy/100/000000/play-button-circled.png">
<img style="width: 35px;" *ngIf="currentState=='start'" src="https://img.icons8.com/cute-clipart/64/000000/stop-squared.png">
</button>
<ul id="dropdown-basic" *dropdownMenu class="dropdown-menu" role="menu" aria-labelledby="button-basic">
<li role="menuitem">
<a class="dropdown-item" *ngIf="currentState=='pause'" routerLinkActive="active" (click)="startTimer()">Start</a>
</li>
<li role="menuitem">
<a class="dropdown-item" *ngIf="currentState=='start'" routerLinkActive="active" (click)="pauseTimer()">Stop</a>
</li>
</ul>
<div>
<span>{{servicesService.fetchDisplay()}}</span>
</div>
</div>
</div>
Component
startTimer() {
this.servicesService.startTimer();
this.currentState = this.servicesService.getCurrentState();
}
pauseTimer() {
this.servicesService.pauseTimer();
this.currentState = this.servicesService.getCurrentState();
}
Upvotes: 0
Views: 1021
Reputation: 1526
component
constructor(private servicesService: ServicesService) {}
public get isPlaying() {
return this.servicesService.getCurrentState() === 'play';
}
public get isPaused() {
return this.servicesService.getCurrentState() === 'pause'
}
HTML
*ngIf="isPlaying"
or
*ngIf="isPaused"
Upvotes: 2
Reputation: 4453
you can define your service as public
constructor(public servicesService: ServicesService) { }
and in your html
*ngIf="servicesService.getCurrentState()=='pause'"
Upvotes: 5
Reputation: 3263
The ngOnInit
is a licefycle hooks and always runs exactly once. If you want to execute something everytime a value changes, you need a different hook. In your case probably ngOnChanges
.
This one gets called everytime a component binding value changes.
For more information on the different hooks I recommend: https://angular.io/guide/lifecycle-hooks
Upvotes: 0