Anwarul Islam
Anwarul Islam

Reputation: 681

How to toggle class in Angular using click event

I have two component in my project. One is header.component and another is sidebar.component. In header.component, I have nav button to open sidebar. So, Basically when someone clicks on the button sidebar will be open. I declared is-open class to my CSS file to add it to the sidebar component's element. So I need to listen click event from header.component and toggle is-open class to sidebar.component

I added a simple js file to my angular project for that like this below:

window.onload = function () {
    let navBtn = document.getElementById('drawerbtn')

    navBtn.addEventListener('click', function () {
        let navDrawer = document.getElementById('navdrawer')
        navDrawer.classList.toggle('is-open')
        console.dir(navDrawer)
    })
}

I checked the console and it's working but in my element is-open class is not adding. How can I do that so easily?

Upvotes: 2

Views: 8900

Answers (2)

This will do the job for you:

In HTML:

<button [ngClass]="isOpen() ? 'is-open': ''" (click)="toggle()">Toggle</button>

In TS file:

isOpened: boolean=false;

isOpen(){
 return this.isOpened;
}

toggle(){
 this.isOpened=!this.isOpened;
}

This can be even simplified as below:

In HTML:

<button [ngClass]="isOpened ? 'is-open': '' (click)="isOpened=!isOpened">Toggle</button>

In TS:

isOpened: boolean=false;

The above code is applying to the same buttons. But what if we have to implement those in different components. Say 3 components - header, side-nave and main-content.Then we have to communicate between components using @Input and @Output to get the state. Below links might help:

https://stackblitz.com/edit/angular-sf-side-menu?file=src%2Fapp%2Fapp.component.ts

https://angular-sf-side-menu.stackblitz.io

Hope this helps.

Upvotes: 1

David Agustin Melgar
David Agustin Melgar

Reputation: 149

The best solution for that is to create a service which it will be tasked to manage the state of the sidebar or whatever you want. In this service you need to create one variable eg: isMenuOpen this variable could be a BehaviorSubject or Subject. Then in the component, you need to subscribe to changes in that variable or directly in your HTML using the async pipe. And lastly, when you need to show the menu, you can switch between 2 CSS classes or directly changing using the property "display" between none and block. Angular is platform agnostic, using window or document you are breaking this agnosticism.

Upvotes: 3

Related Questions