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;
}
Angular6 using the renderer2 without any variables and a clean template:
template:
in ts:
One could put this in a directive too ;)
If you want to toggle text with a toggle button.
HTMLfile which is using bootstrap:
TS file:
This Should work for you:
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-
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.
ngClass
should be wrapped in square brackets as this is a property binding. Try this:In your component:
Hope that helps.