2017-06-06 69 views
1

我有一個側面導航欄,其中每個導航欄中都有一個進度欄。 這是模塊化結構 -動態更改css而無需在Angular2中重新加載頁面

MainFile 
    -Children1 
     -children1.html 
     -children1.component.ts 
    -Children2 
     -children2.html 
     -children2.component.ts 
    -Children3 
     -children3.html 
     -children3.component.ts 
    -ProgressIndicator 
     -progressIndicator.html 
     -progressIndicator.component.ts 
    -main.html 
    -main.component.ts 

裏面progressIndicator.html,我有這樣的代碼,

<div class="progress"> 
    <div [ngStyle]="{'width':getProgress()}" class="progress-bar" role="progressbar" aria- 
     valuenow="70" aria-valuemin="0" aria-valuemax="100"> 
     <span class="sr-only">70% Complete</span> 
    </div> 

而我progressIndicator.component.ts

currentPage = ''; 
progressBar = ''; 
//getting current route name using 'this.route.url' and updating 'currentPage' property in 
constructor. 
getProgress(){ 
    if(currentPage === 'children1'){ 
     return progressBar = '25%'; 
    } 
    if(currentPage === 'children2'){ 
     return progressBar = '50%'; 
    } 
} 

我成功地獲得當前頁面,作爲'children1.html'或'children2.html',基於當前頁面我想改變div的寬度與類'progress-bar',我用

[ngStyle]="{width:getProgress()}" 

但只有當頁面重新加載時,纔會生效,其中angular2是SPA不會發生。 幫助我找到一種更好的方式,當我從'children1'移動到'children2'時,'getProgress()'生效並更改樣式。

回答

2

你應該從方法返回的整體風格對象:

組件

getStyle():any{ 
    return { width: getProgress() }; 
} 

模板:

[ngStyle]="getStyle()"; 

這樣一來,整個getStyle方法將被調用在更改檢測時,即使如此,應該更新您的樣式你不會重新加載(因爲,如你所說,你不應該重新加載)。

+0

它仍然只在重新加載。 :( –

2

返回您的呼叫中的全鍵:值對。同時將currentPage賦值給你的函數。

HTML

[ngStyle] = "getProgress()" 

TS

getProgress(){ 
    let currentPage = this.router.url; 
    let progressBar; 
    if(currentPage === 'children1'){ 
     progressBar = {'width' : '25%'}; 
    } 
    if(currentPage === 'children2'){ 
     progressBar = {'width' : '50%'}; 
    } 
    return progressBar 
} 

Here是一個很好的寫了上ngStyle使用。

+0

它仍然只是在重新加載: –

+1

@MichaelPhilips。答案已經更新。這是否解決了這個問題? – Ethilium

+0

不,它只會重新加載頁面:( –

相關問題