2017-02-10 81 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