Angular 6 How to add and remove class using Angular Renderer2

I am trying to use angular Renderer2 to add and remove a class in HTML template. Here I am facing the difficulties:

  1. to add the class once component will load
  2. Only the selected item should have the class

I have created a demo in stackblitz. Please click here to see code.

Thank you.

<div class="tabs">
<a href="#" (click)="selectTab($event)">Tab 1 </a>
<a href="#" (click)="selectTab($event)">Tab 2 </a>
<a href="#" (click)="selectTab($event)">Tab 3</a>

constructor(private render:Renderer2){}
selectTab(event:any) {
- - Source


answered 1 week ago Hrishikesh Kale #1

what about [ngClass]="{'test': selectedTab== 1}"

I have created a ts variable calling selectedTab and declared as number

in HTML I've used [ngClass]="{'test': selectedTab== 1}" so when selectedTab = 1 test class will be added .

and on click method I have called selectTab(2) sending clicked tab parameter and handled this function in ts like

selectTab(selectedTab) {
if(selectedTab == 1){
  this.selectedTab = 1;
}else if(selectedTab == 2){
  this.selectedTab = 2;
  this.selectedTab = 3;
}  }

comments powered by Disqus