Angular ngClass and click event for toggling class
This should work for you.
In .html:
<div class="my_class" (click)="clickEvent()"
[ngClass]="status ? 'success' : 'danger'">
Some content
</div>
In .ts:
status: boolean = false;
clickEvent(){
this.status = !this.status;
}
Instead of having to create a function in the ts file you can toggle a variable from the template itself. You can then use the variable to apply a specific class to the element. Like so-
component.html -
<div (click)="status=!status"
[ngClass]="status ? 'success' : 'danger'">
Some content
</div>
So when status is true the class success is applied. When it is false danger class is applied.
This will work without any additional code in the ts file.
EDIT: Recent versions of angular require the variable to be declared in the controller -
component.ts -
status: boolean = false;
Angular6 using the renderer2 without any variables and a clean template:
template:
<div (click)="toggleClass($event,'testClass')"></div>
in ts:
toggleClass(event: any, className: string) {
const hasClass = event.target.classList.contains(className);
if(hasClass) {
this.renderer.removeClass(event.target, className);
} else {
this.renderer.addClass(event.target, className);
}
}
One could put this in a directive too ;)
ngClass
should be wrapped in square brackets as this is a property binding. Try this:
<div class="my_class" (click)="clickEvent($event)" [ngClass]="{'active': toggle}">
Some content
</div>
In your component:
//define the toogle property
private toggle : boolean = false;
//define your method
clickEvent(event){
//if you just want to toggle the class; change toggle variable.
this.toggle = !this.toggle;
}
Hope that helps.