2017-02-10 208 views
0

我试图更改按钮图像src并将用户路由到另一个页面。这是我尝试过的。Angular 2单击事件:更改图像,然后更改路由

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); 
    } 
} 

它不会改变图像的src,但它确实路由用户到正确的页面。有没有办法做到这一点?

谢谢!

+2

如果图像发生变化,您会如何知道图像是否会变化?如果您要从该组件中取消路由,那么甚至需要更改家庭组件中的映像? :) – Alex

+0

@ AJT_82它不会让我发布图像,否则我会告诉你的目标。我们有两个图像(1)有阴影的六角形和(2)没有阴影的六角形。我们试图在点击时创建一个按下按钮,然后路由到页面。那有意义吗?如果我愿意尝试一种更好的方式,但由于按钮是六角形,这很难。 – JessySue

+0

嗯,它不会工作,因为'goToFinishing'更改图像和路由远离组件,新图像没有时间呈现之前,你是路由:) – Alex

回答

1

这是“不变”,因为只要您导航到路由器上的其他路径,旧视图就会被销毁,从而导致所有状态都丢失。

您需要分离应用程序的状态以保留对特定视图的更改。为此,您需要创建一个提供程序来跟踪应用程序状态,将其注入到需要使用状态的视图/组件中,并在模板中引用提供程序中的相应状态变量。

实施例:

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> 

确保将AppProvider类导入并添加到@NgModule的声明中,以便依赖项注入可以工作。

希望它有帮助。


修订解答: 添加到路由改变的延迟,因此该图像的变化,可以看出第一。

+0

感谢您的帮助。但是,它仍然会路由到_before_页面,您会看到图像中的更改。 – JessySue

+0

请参阅我的更新答案,其中路由更改添加了1秒的延迟,因此用户可以首先看到图像更改。 – ablopez

+0

谢谢!我昨天终于尝试了'setTimeout',它工作。 – JessySue