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");
}
3
  • Downvoted because questions should contain the code needed for answering the question inside of the question. Not with an external link. Commented Jan 13, 2019 at 8: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. Commented Jan 13, 2019 at 8: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. Commented Jan 13, 2019 at 11:51

1 Answer 1

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;
}  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @Hrishikesh Kale. This is the one approach to solve the problem. But I was wondering how to solve using Renderer2.
yes absolutely this answer will help you stackoverflow.com/questions/48674025/…
that's great happy coding brother.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.