In Angular, I would like to use ngClass
and click event to toggle class. I looked through online but some are angular1 and there isn't any clear instruction or example. Any help will be much appreciated!
In HTML, I have the following:
<div class="my_class" (click)="clickEvent($event)" ngClass="{'active': toggle}"> Some content </div>
In .ts
:
clickEvent(event) { // Haven't really got far var targetEle = event.srcElement.attributes.class; }
yes , you can do it.
Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With