1

I want to add active and open classes to the li when clicked and remove those classes if clicked again

 <li id="xx" class="treeview" (click)="menuToggle($event)">
 <li>

ts

 menuToggle(event: any) {
  this.renderer.addClass()
}
2
  • you can use NgClass angular.io/api/common/NgClass Commented Mar 26, 2019 at 7:11
  • 1
    event.target.classList.toggle('active') Commented Mar 26, 2019 at 7:12

6 Answers 6

3

You can use template reference variable to toggle classes in template:

<li #myLi class="treeview" (click)="myLi.classList.toggle('my-class')"><li>

Or if you want to do it in the component file (maybe if you want to add more logic):

component.ts

toggleClass = (event) => {
    event.target.classList.toggle('my-class');
}

template.html

<li class="treeview" (click)="toggleClass($event)"><li>
Sign up to request clarification or add additional context in comments.

Comments

1

you can try like this

HTML

<li id="xx" [ngClass]="classFlag === true ? 'treeview' : '' " (click)="menuToggle($event)">
<li>

TS

 classFlag: boolean = false;
 menuToggle(event: any) {
    this.classFlag = !this.classFlag ;
 }

Comments

1

You can try these, No need to write specific function for it

<li [ngClass]="classFlag ? 'treeview' : '' " (click)="classFlag ? classFlag = false : classFlag = true">test</li>

Comments

0

I fixed it by using plain old Javascript:

// Find current active item
var myElement = document.getElementsByClassName('active');

// If found, remove the css class 'active'
if(myElement[0])
  myElement[0].classList.remove("active");

// Get the new active item
var currentElement = document.getElementById('message_' + messageId);
// Set the css class 'active'
currentElement.classList.add("active");

Comments

0

HTML:

 <li id="xx" class="treeview" (click)="menuToggle($event)">
 <li>

Component:

menuToggle(event:any) {
  event.target.classList.add('class3'); // To ADD
  event.target.classList.remove('class1'); // To Remove
  event.target.classList.contains('class2'); // To check
  event.target.classList.toggle('class4'); // To toggle
}

Comments

0

You should give an "active" property , something like this:

items = [
  {name:'a', active:false},
  {name:'b', active:false}
];

And inside the template:

<li *ngFor="let item of items" (click)="menuToggle(item)" [ngClass]="{'active': item.active}">{{ item.name }}</li>

And finally the menuToggle() method just toggles the active state of the clicked item:

menuToggle(){
 item.active = !item.active;
}

Comments

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.