Reputation: 753
I am trying to change a button image src AND route the user to another page on click. Here is what I have tried.
home.component.html
<button class="hexagon"
(click)="gotoFinishing()">
<img [src]="imgsrc">
</button>
home.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
templateUrl: 'home.component.html'
})
export class HomeComponent {
constructor( private router: Router) { }
imgsrc="test.png";
gotoFinishing(){
this.imgsrc="test2.png";
let link = ['/finishing'];
this.router.navigate(link);
}
}
It does not change the image src, but it does route the user to the correct page. Is there a way to do this?
Thanks!
Upvotes: 0
Views: 7822
Reputation: 850
It's "not changing" because as soon as you navigate to another path on the router, the old view is destroyed and thus all state is lost.
You need to decouple the state of your application in order to preserve changes to particular views. To do that, you'll need to create a provider for keeping track of the app state, inject it into the views/components you'll need to use state on, and in the template reference the corresponding state variable within the provider.
Example:
app.provider.ts
@Injectable()
export class AppProvider {
public state = {
Home: {
imgsrc: 'test.png
}
};
}
home.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AppProvider } from './app.provider.ts';
@Component({
templateUrl: 'home.component.html'
})
export class HomeComponent {
constructor(
private router: Router,
public appProvider: AppProvider
) { }
gotoFinishing(){
this.appProvider.state.Home.imgsrc="test2.png";
setTimeout(() => {
this.router.navigate(['/finishing']);
}, 1000);
}
}
home.component.html
<button class="hexagon" (click)="gotoFinishing()">
<img [src]="appProvider.state.HomeComponent.imgsrc">
</button>
Be sure to import and add the AppProvider class into the declarations of your @NgModule so the dependency injection can work.
Hope it helps.
UPDATED ANSWER: Added a delay to the routing change so the image change can be seen first.
Upvotes: 1