Reputation: 2970
I have a side navigation bar, wherein there is progress bar in each nav. This is modular structure-
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
Inside progressIndicator.html, I have this code,
<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>
And my 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%';
}
}
I am successfully getting the current page, as 'children1.html' or 'children2.html', based on the current page I want to change the width of div with class 'progress-bar', I used
[ngStyle]="{width:getProgress()}"
but it takes effect ONLY if page reloads, which angular2 being SPA doesn't happen. Do help me in finding a better way that when I move from 'children1' to 'children2', the 'getProgress()' takes effect and changes the style.
Upvotes: 2
Views: 1366
Reputation: 1234
Return the full key:value pair in your call. Also bring the assigning of currentPage into your function.
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 is a good write up on ngStyle use.
Upvotes: 2
Reputation: 8731
You should return the whole style object from a method:
Component
getStyle():any{
return { width: getProgress() };
}
Template:
[ngStyle]="getStyle()";
This way, the whole getStyle
method will be called upon change detection, which should update your style even if you don't reload (because, as you said, you should never have to reload).
Upvotes: 2