1

i've been struggling with the simplest thing... i need to add a class to a <div> when i click on, let's say, a button. I've been looking online and here on stackoverflow for hours and all i can find is some overcomplicated examples with ngFors that i cannot (and i am not able to) deconstruct to fit it to what i need.

I'm looking to achieve something as simple as this (jquery) in angular2/typescript:

 $(".button").click(function() {  
    $(".element").addClass("active");      
  });

i have a component folder with the usual html,scss, and ts file. this function doesn't need to be global or anything weird.

i can't believe how something as simple as this has become so complicated to achieve with modern frameworks.

any help is greatly appreciated!

3
  • imo the best way to achive that would be creating the decorator. Decorator should be added to every element that you want to behave in this way. Decorator will addClass to element using HostListener onClick Commented Oct 4, 2019 at 8:25
  • @MaciejWójcik that's a bit overkill and it's assuming you have the need for it on several html elements, which I think isn't the case here Commented Oct 4, 2019 at 8:27
  • sure, that depends on the needs (the amount of elements) Commented Oct 4, 2019 at 8:40

2 Answers 2

2

It's simple. you need to use ngClass like this :

<button (click)="isActive = true">Your button</button>
<div class="element" [ngClass]="{'active': isActive}"

https://angular.io/api/common/NgClass

Sign up to request clarification or add additional context in comments.

1 Comment

Or even simpler: [class.active]="isActive".
1

It's not complicated at all : you just do not know where/what to look for.

First solution :

<div [class.myClass]="isClicked"></div>
<button (click)="isClicked = true">Click me</button>

Second solution

<div #myDiv></div>
<button (click)="myDiv.className='myClass'">Click me</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.