catsdev
catsdev

Reputation: 83

ToggleClass('active') on Angular and Typescript

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!

Upvotes: 2

Views: 14296

Answers (3)

Md. Shahidul Islam
Md. Shahidul Islam

Reputation: 330

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.

Upvotes: 2

Himanshu Jangid
Himanshu Jangid

Reputation: 385

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">

Upvotes: 1

SiddAjmera
SiddAjmera

Reputation: 39432

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.

Upvotes: 7

Related Questions