How To Toggle Class Only Current Element Angular2
here is my code examples. In my case toggle class works for every li element
Solution 2:
You can make a directive and use @HostBinding
Example
import { Directive, ElementRef, HostBinding } from '@angular/core';
@Directive({
selector: '[my-directive]'
})
export classMyDirective{
@HostBinding('class.active') isActive = false;
toggle() {
this.isActive = !this.isActive;
}
}
Use like this :
<li [my-directive] (click)="toggle()">blah</li>
Solution 3:
You should store the active variable per item, not on the whole component with all the li's:
<li *ngFor="let x of nav" (click)="x.active = !x.active"... >
You can use the following code in your template to display active class:
[class.active]="x.active"
Solution 4:
You have to add an active
property to your nav interface/class:
<ulclass="nav nav-pills pull-right"><li *ngFor="let x of nav"class="presentation"
(click)="nav.active = !nav.active"
[class.active]="nav.active"
><ahref="#">{{x.menu}} </a></li></ul>
But seeing as that you are trying to select a navigation item, i would guess that you only want to select one. You have to change your template to something like this:
<ulclass="nav nav-pills pull-right"><li *ngFor="let x of nav"class="presentation"
(click)="active = x"
[class.active]="x === active"
><ahref="#">{{x.menu}} </a></li></ul>
In your component you should change your active
declaration from boolean
to your nav item class/interface/any
Solution 5:
You can use the HostListener for the directive to be pure
export classMyDirective{
@HostBinding('class.active') isActive = false;
@HostListener('click', ['$event'])
onClick(e) {
this.isActive = !this.isActive;
}
}
And use the html
<li[my-directive]>blah</li>
Post a Comment for "How To Toggle Class Only Current Element Angular2"