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;