Leveraging the Power of JavaScript within Angular 12

Currently, I am in the process of learning how to utilize Angular 12 and am attempting to create a sidenav. While I am aware that I can use angular material for this task, I would prefer not to incorporate the associated CSS.

My goal is to integrate this particular feature into my project. However, I am struggling to comprehend how to convert the provided JS code to be compatible with an Angular 12 project.

I have stored the JavaScript code in a file named menu.js within my assets/js folder. Nonetheless, I am uncertain about how it should be integrated with the component.js file since it does not consist of an actual function but rather 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");
});

Answer №1

Your current code may be considered outdated. It's time to embrace the Angular way of doing things.

Essentially, what your code is achieving is toggling a CSS class on an element when clicked. Here's how you can achieve this in an Angular environment:

In your HTML file:

<button (click)="toggleSidebar()">Toggle Sidebar</button>
<!-- The show-me class gets 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;
}

You can then define your animation styles in your .styles file:

.sidebar {
  // Styles
}

.sidebar.show-me {
  // Additional styles
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add the variable's value to the input field

It is necessary for me to concatenate a numeric value, stored in a variable, with the input fields. For example: var number = 5; var text = $("#dropdown_id").val(); I wish to append the value of the variable 'number' to 'dropdown_id' ...

Datatables stands out by emphasizing rows across all paginated pages

Encountering an issue with the Datatables plugin when attempting to highlight rows on paginated pages beyond the first one. In the JavaScript code below, you can see where I have commented out adding the class info to all rows. When this is done and you n ...

What is the comparable alternative to promise<void> in observables?

I've been working with Angular using TypeScript and I'm attempting to return a promise from an observable. What is the correct way to accomplish this? So far, I have tried the following: of(EMPTY).toPromise() // error: Promise<Observable<n ...

Module `coc-tsserver` not found (error ts2307)

Working on a project using NeoVim with CoC for TypeScript development in a yarn-3 pnp-enabled environment. Suddenly, the editor stopped recognizing imports and started showing errors for non-existent modules (refer to the screenshot). I've already set ...

What can cause a problem with the reduce function that populates an empty object with keys in TypeScript?

I've encountered an issue with a function that is meant to reduce an object. The problem lies in using the reduce method to assign the values of acc[key] as object[key], which is resulting in errors in the code. I am trying to avoid using any specific ...

encountering difficulties calling setAttribute within a function

I am encountering an issue while attempting to use setAttribute() within toggleDiv(). My IDE does not seem to recognize the function and is throwing an error. How can I resolve this problem so that the function is recognized? This specific case relates t ...

Access an HTML element and using JavaScript to make changes to it

As a new web developer, I am eager to create a grid of file upload zones on my site. I have decided to use DropZone.js for this project. I have customized DropZone and added multiple drop zones in the HTML. The grid layout consists of four rows with four ...

The Angular application remains unminified after being built with the "prod" flag

Currently, my Angular 7 project is configured for production build with the settings optimization=true and buildOptimizer=true. Below, you will find a snippet of the full production configuration from my angular.json file. I have set up an automated build ...

Challenges with character encoding in NextJS

I am currently dealing with a line of code that creates a dynamic route. <Link href={`/bundeslander/${urlName}`} ><div className=" text-blue-400">{state.name}</div></Link> The variable urlName is generated by fetching dat ...

What could be causing my SVG bezier curves to malfunction in Firefox?

Encountered an issue today where diagrams I have generated are not functioning properly in Firefox when created using the getPointAtLength method. Here is a demonstration of the problem: http://jsfiddle.net/xfpDA/9/ Please take note of the comments at th ...

The removeEventListener method in JavaScript fails to function properly

On my website, I have a unique feature where clicking an image will display it in a lightbox. Upon the second click, the mouse movement is tracked to move the image accordingly. This functionality is working as intended, but now I'm faced with the cha ...

The Vuetify accordion template is not appearing due to a v-for loop issue in Nuxt.js

My goal is to set up an FAQ page using Nuxt.js. The template I obtained from Vuetify doesn't display correctly on my localhost. Instead, I'm encountering errors. If I replace 'v-for "(item,i) in 5" : key="i"' as per the template source ...

A Guide to Connecting a JavaScript File to an HTML Page with Express and Node.js

Struggling with integrating my JavaScript file into my simple NodeJS app. Traditional methods like placing the script in the header doesn't seem to work with Node. I've attempted using sendFile and other approaches, but none have been successful ...

Error: Unable to access the property 'fontSize' as it is undefined

<!DOCTYPE HTML> <html> <head> <title>Interactive Web Page</title> <link id="mycss" rel="stylesheet" href="mycss.css"> <script> function resizeText(size) { va ...

Dynamic Code for Removing List Items Based on Date

I need assistance in resolving an issue with my company's website design and function. Specifically, I am working on a page that displays a list of events where employees will be present throughout the year. Here is an example: <div class="contai ...

What is the best way to transform an array of objects into a nested array through shuffling

I am dealing with a diverse array of objects, each structured in a specific way: data = [ { content: { ..., depth: 1 }, subContent: [] }, { content: { ..., depth: 2 ...

Unable to locate a type definition file for module 'vue-xxx'

I keep encountering an error whenever I attempt to add a 3rd party Vue.js library to my project: Could not find a declaration file for module 'vue-xxx' Libraries like 'vue-treeselect', 'vue-select', and 'vue-multiselect ...

Ways to effectively handle diverse Angular module dependencies

Although I am still new to Angular, I have been striving to write more modular code and rely less on cramming logic into the controller. Instead, I have been utilizing independent services. However, a recurring issue I am facing is having to re-declare the ...

Delete JavaScript functions and events from memory once the JavaScript code has been removed from the HTML file

I am encountering a situation with my website where popups loaded via ajax also load JavaScript code, which I want to remove when the popup is closed. The main site code looks like this: <body> ... <div id="popup" style="display:none"> < ...

Determining when it is necessary to loop over a variable

I'm facing a situation where I have two different responses based on whether we need to loop over an object or just display a variable. My attempted solution involved using ng-if else, but unfortunately, it didn't work as expected. This is the ...