1

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");
});
3
  • Have you instead considered converting this to “angular” syntax, as in using component variables in combination with directives like ngClass and similar to achieve the desired functionality? Commented Aug 4, 2021 at 15:32
  • Could you help me understand how to convert it? Or provide a example I can use to understand. Commented Aug 4, 2021 at 16:08
  • You need to make an attempt first. Use something like StackBlitz. Create an Angular application. Create some components. Create variables on the components in combination with ngClass and event binding and component interaction. You could create components for the menu and menu items, track values of open/closed, use events and input to manipulate child components, You could also try to find tutorials to help build out a menu component. Commented Aug 4, 2021 at 16:14

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this was the perfect example for me to understand what changes to make...

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.