Reputation: 15
I'm learning to use Angular 12 and trying to build a sidenav. I know I can use angular material, but I don't want to use the css associated with it.
I'd like to use this in my project. But can't understand how to convert the JS to be used in the angular 12 project.
I've placed the javascript in a menu.js under my assets/js folder. But can't understand how it's used with the component.js since it isn't a actual function, but a document.queryselectorall.
let arrow = document.querySelectorAll(".arrow");
for (var i = 0; i < arrow.length; i++) {
arrow[i].addEventListener("click", (e)=>{
let arrowParent = e.target.parentElement.parentElement; //selecting main parent of arrow
arrowParent.classList.toggle("showMenu");
});
}
let sidebar = document.querySelector(".sidebar");
let sidebarBtn = document.querySelector(".bx-menu");
console.log(sidebarBtn);
sidebarBtn.addEventListener("click", ()=>{
sidebar.classList.toggle("close");
});
Upvotes: 1
Views: 2258
Reputation: 57225
Your code is old school. You need to get used to the Angular approach.
Basically what your code is doing is toggling a CSS class on an element on click. Here's how you do that in Angular:
In your HTML file:
<button (click)="toggleSidebar()">Toggle Sidebar</button>
<!-- the show-me class is added when showSidebar is true -->
<div class="sidebar" [class.show-me]="showSidebar">I am a sidebar</div>
In your .ts file:
showSidebar = false;
toggleSidebar() {
this.showSidebar = !this.showSidebar;
}
And then add your animation styles in your .styles file:
.sidebar {
// styles
}
.sidebar.show-me {
// styles
}
Upvotes: 2