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

Utilizing Ionic Storage to set default request headers through an HTTP interceptor in an Angular 5 and Ionic 3 application

I'm attempting to assign a token value to all request headers using the new angular 5 HTTP client. Take a look at my code snippet: import {Injectable} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ...

Encountering a TypeScript error in Vue 3 when trying to assign a type of '($event: any) => void' to an event listener

Snippet of component code: <h2 @click="handleEvent(post.id)">{{ post.title }}</h2> function handleEvent(id: number) { router.push("/post/" + id); } Error message in TypeScript: Type '($event: any) => void' i ...

In order to emphasize the chosen list item following a component refresh

SCENARIO: Let's consider a scenario where I have a component named list, responsible for displaying a list of all customers. Within this list, certain conditions are set up as follows: 1) Initially, the 1st list-item (e.g. Customer 1) is selected by ...

Are promises perpetually in a state of limbo? (incorrect format

As a newcomer to node.js, express, and ES6, I am learning the ropes and trying to write cleaner, more efficient code using ES6 functions and promises. One issue I'm facing is with inherited functions and values, particularly next(). Here's the co ...

Updating array object properties within nested for loops in JavaScript can be challenging

Exploring nested loops: for(let i = 0; i < availabilities.length; i++){ if(availabilities[i].round === 1){ // Identify objects with the same event_team_user_id and update status property let indices = helperService.findArrayIndices( ...

Compilation of various Typescript files into a single, encapsulated JavaScript bundle

After researching countless similar inquiries on this topic, I have come to the realization that most of the answers available are outdated or rely on discontinued NPM packages. Additionally, many solutions are based on packages with unresolved bug reports ...

Having trouble with my JavaScript code in Visual Studio because of a bundler issue. It's throwing an Uncaught ReferenceError for trying to access a variable before initialization

My AJAX request looks like this: $.ajax({ method: 'GET', url: '/api/some-data', headers: { 'Content-Type': 'application/json' }, success: function(data) { if (data != null) { var userDat ...

``I am experiencing slow loading times with Google Maps JS when using

When accessing Google Maps on Safari, zooming in can be frustratingly slow on both Windows and Mac. The experience feels glitchy, with the zoom starting, freezing, then finally finishing. In comparison, Chrome provides a much smoother and faster zooming ex ...

What makes components declared with "customElements.define()" limited in their global usability?

I've been tackling a project in Svelte, but it involves some web components. The current hurdle I'm facing is with web components defined using the customElements.define() function in Typescript, as they are not accessible unless specifically im ...

Checking for an exact value using the includes() method in JavaScript - a comprehensive guide

In order to populate checkboxes based on a string delimited with pipes, I have been using the includes() method. However, I am encountering an issue where items with similar names are both marked as true because they share the same string, even if they are ...

"Maximizing Space: A Guide to Setting BootStrap Navbar on the Right Side of the Page with Dropdown Width

Take a look at the image below. There is a navbar toggle button on the upper right corner of the page. When I expand it, the dropdown items occupy the entire width of the page, causing an issue where clicking anywhere within the red box triggers the dropdo ...

Is annotation functionality available in version 3 of Chart.js?

In the previous version 2 of the chart, I utilized 'annotation' within options. However, after upgrading to version 3, it seems to have stopped working and I am unable to locate any information about this in the documentation. The following code ...

What is the best way to iterate through an object and display each item as <li></li> within another <li>?

After retrieving a specific object from an express endpoint and seeing it on the console, I need to figure out how to map it in order to display a jsx that resembles this <li>keys</li> : <li>values</li> For example: Company: DML ...

Steps to globally modify the font in Ionic

In my Ionic app running version 3.9.2, I am attempting to customize the default font to a specific custom one. After researching, I discovered that I need to set the font face in the app.scss file located within the app folder. Here is the code snippet I ...

React's createPortal function does not place the child element inside a container

My new to-do list app in React has a simple functionality where clicking a button should add a new item to the list. However, I am facing an issue with the createPortal method not triggering the UI to render the new item. Here's the code snippet causi ...

Tips on assigning a data-id attribute

After a click event, I am attempting to dynamically set the data-id and/or value of a span using my JavaScript file. <span id="test"></span> Here is an example of the JavaScript code: nextLink: function(event) { $('#test').val ...

Is it possible for the controller of a modal window to have access to functions within the parent controller

If you were to launch a modal window using $modal.open from an angular directive, would the modal window be able to access functions defined within the parent directive? Below is the code for the directive controller: function parentFunction() { re ...

Hiding Clear button in Autocomplete to display only text

Exploring react-virtualization and Autocomplete features here. I currently have a list set up to display multiple texts when a checkbox is selected. Here's the code snippet: https://codesandbox.io/s/material-demo-forked-1qzd3?file=/demo.tsx The goal ...

Is there a way to conceal an element using identical markup with jquery?

Having trouble with two custom dropdown lists that share the same markup. Ideally, only one should be visible at a time. However, both are currently opening simultaneously. Additionally, I need them to close when clicking outside of the list. It's ne ...

Graph only displays data after button is clicked

I have been working on customizing this jsfiddle to display database data. Check it out here: http://jsfiddle.net/jlbriggs/7ntyzo6u/ Using JSON, I am fetching data from my database and editing chart1 to display the database data: var chart, chartOption ...