2

Anyone knows how can I do something like this with Angular?

$('button').click(function(){
  $('button').toggleClass('active');
  $('.title').toggleClass('active');
  $('nav').toggleClass('active');
});

Thank you very much!

1

3 Answers 3

7

You can use something like this([class.className]="conditionThatResolvesToABoolean", or [ngClass]) for doing this:

<div [class.active]="classApplied">
  Here's some text
  <button (click)="toggleClass()">Toggle Class</button>
</div>

And in your Template:

import { Component } from '@angular/core';

@Component({...})
export class AppComponent  {
  classApplied = false;

  toggleClass() {
    this.classApplied = !this.classApplied;
  }
}

Here's a Sample StackBlitz for your ref.

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

2 Comments

How about if I have to toggle the class on multiple elements. classApplied toggles them on every instance simultaneously...
If your instances are a part of a list, each object in that list backing up an instance could additionally have a property that determines whether the class should be applied or not. And you could use the index of the item in the list to only set this property for the item present at that index. Hope that makes sense. If not, I'd urge you to create a new question thread and I'd be happy to answer in there. :)
2

In my case i have added Toggle class like that:

Component-HTML

<button (click)="darkMode()">Dark Mode</button>

Component-TS

 darkMode() {
    const themeClass = document.querySelector('body');
    themeClass?.classList.toggle('dark-mode');
 }

And its work for me.

Comments

1

This is the Typescript code to solve this problem

@Component({
      selector: 'app-navbar',
      templateUrl: './navbar.component.html',
      styleUrls: ['./navbar.component.scss']
    })
    export class NavbarComponent implements OnInit {
    
      is_active = "";
      constructor() { }
    
      ngOnInit(): void {
      }
    
      toggleNav(){
        if(this.is_active){
          this.is_active = "";
        }
        else{
          this.is_active = "is-active";
        }
      }
    
    }

This is my way to do it now we can use is_active property in the html code

<div class="navbar-burger {{is_active}}" role="button" (click)="toggleNav()" data-target="navbarExampleTransparentExample">

1 Comment

fo something like this u can use public isActive = false; remove toggleNav func, and in html: [class.is-active]="isActive" (click)="isActive = !isActive"

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.