0

I would like to add class when receiving a click event in template

What I do is something like this:

<div
      #myDiv
      (click)="myDiv.classList.add('my-class')"
></div>

but this does not work.

How can I make it works? Thanks

kk-at-cbx
  • 329
  • 3
  • 10
  • 1
    Does this answer your question? [angular - Adding a class to a DOM element when clicked](https://stackoverflow.com/questions/42809368/angular-adding-a-class-to-a-dom-element-when-clicked) – Pushkin Jan 14 '21 at 03:41
  • I would like to perform the code in html template. not inside component script – kk-at-cbx Jan 14 '21 at 03:58

1 Answers1

1

You can do the following:

<div [ngClass]="classStr"
      (click)="classStr='my-class'">
</div>

you will have to add classStr to your component (just declare it - classStr: string; inside the component)

notice that this will only add the class once, not toggle it, if you want to toggle, you will have to do something like:

<div [ngClass]="classStr"
   (click)="classStr = classStr === 'my-class' ? '' : 'my-class' ">
</div>
Moshezauros
  • 2,493
  • 1
  • 11
  • 15