0

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>
</div>


constructor(private render:Renderer2){}
selectTab(event:any) {
this.render.addClass(event.target,"test");
}
Md. Amanullah
  • 311
  • 4
  • 15
  • Downvoted because questions should contain the code needed for answering the question inside of the question. Not with an external link. – David Walschots Jan 13 '19 at 08:40
  • It seems you've also edited your original code with Hrishikesh Kale's suggestion, meaning the code that lead to your question is no longer available. – David Walschots Jan 13 '19 at 08:43
  • Yes, this edit was just to check Hrishikesh Kale's approach, no intention to change the code. I have edited my question as well. – Md. Amanullah Jan 13 '19 at 11:51

1 Answers1

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;
}else{
  this.selectedTab = 3;
}  }
}
Hrishikesh Kale
  • 6,140
  • 4
  • 18
  • 27