'Show active Tab in angular
I am trying to show the active tab in an Angular app. The trouble is that the tab is located in a sub header where as the component which dictates which tab is active is in another location. My code will explain better.
Sub header HTML
<div class="col-6">
<div class="action" > Contributions and savings </div>
<div class="action"> Retirement strategy </div>
</div>
Sub header TS
ngOnInit() {
localStorage.getItem('step');
}
Component HTML
<app-subheader></app-subheader>
Component TS
localStorage.setItem('step', JSON.stringify(this.step));
Now as "Step" is updated in localStorage, I need to check in the subheader.ts everytime the value changes so I can update the tab to show active css. Any ideas, I am stuck here. How can I check for when the value changes? NgOninit only does it once.
Solution 1:[1]
For making active tab logic you can do this :
HTML:
<button (click) = "clickTab(1)" [ngClass]="{'active': step === 1}">ONE</button>
<button (click) = "clickTab(2)" [ngClass]="{'active':step === 2}">TWO</button>
TS :
ngOnInit() {
this.step == 1;
localStorage.setItem('step', JSON.stringify(this.step));
}
clickTab(stepValue){
this.step = stepValue;
localStorage.setItem('step', JSON.stringify(this.step));
}
CSS:
.active, .btn:hover {
background-color: #666;
color: white;
}
Here is the working example:
Solution 2:[2]
- The above method is correct but the #stackblitz link is not clear, I have added the link as below
- Here is the working example: https://stackblitz.com/edit/angular-wdw6sl
HTML:
<button [class]="btnActive === 'one' ? 'active' : ''" (click)="activeBtn('one')">ONE</button>
<button [class]="btnActive === 'two' ? 'active' : ''" (click)="activeBtn('two')">TWO</button>
<button [class]="btnActive === 'three' ? 'active' : ''" (click)="activeBtn('three')">THREE</button>
CSS:
.active {
background-color: red;
color: #fff;
}
TS:
btnActive: string = 'one';
ngOnInit() {}
activeBtn(btnActive: string) {
this.btnActive = btnActive;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Prashant Pimpale |
Solution 2 |