Switching jQuery toggle effects to Angular framework

My current jQuery animations for toggling the sidebar are as follows:

$('.sa-fixedNav_toggle').click(function () {
        $('.sa-fixedNav_positon').toggleClass('sa-fixedNav_size-grow')
        $('.pa-content_layout').toggleClass('pa-content_push-right')
        $('.sa-fixedNav_expand-button').toggleClass('sa-fixedNav_expand-nav')
        
        if($('.sa-fixedNav_positon').width() == 78) {
            sideNavContentShow()
        }
        else {
            setTimeout(() => {
                sideNavContentHide()
            },150);
        }
    })
  function sideNavContentShow () {
      $('.sa-fixedNav_content-expand').removeClass('hidden');
      $('.sa-fixedNav_option-expand-icon').removeClass('hidden');
       $('.sa-fixedNav_option-expandDown-icon').removeClass('hidden')
  }
    function sideNavContentHide () {
        $('.sa-fixedNav_content-expand').addClass('hidden');
        $('.sa-fixedNav_option-expand-icon').addClass('hidden');
        $('.sa-fixedNav_option-expandDown-icon').addClass('hidden')
  }
    
    $('.sa-fixedNav_nav-links').click(function () {
        $('.sa-fixedNav_option-expandDown-icon').toggleClass('sa-fixedNav_expand-hidden')
        $('.sa-fixedNav_option-expand-icon').toggleClass('sa-fixedNav_expand-hidden')
    })

I am now looking to replicate this functionality in Angular. I have attempted to use Renderer2 and @ViewChild, but there is no direct equivalent to toggleClass and I cannot find a method to retrieve the width. How would you recommend achieving this in Angular?

Answer №1

If you want to achieve this functionality, you can follow the steps below with the help of @ViewChild(), ElementRef, and classList:

<div #someelementone class="some-element-class toggle-class-one">
  Test
</div>
<div #someelementtwo class="some-element-class toggle-class-two">
  Tes2
</div>
<div #someelementthree class="some-element-class toggle-class-three">
  Tes3
</div>

<button (click)="updateElementClasses()">Toggle Classes</button>

In your component's typescript file:

export class AppComponent {
  @ViewChild('someelementone') someElementOne: ElementRef;
  @ViewChild('someelementtwo') someElementTwo: ElementRef;
  @ViewChild('someelementthree') someElementThree: ElementRef;

  updateElementClasses() {
    this.toggleClass(this.someElementOne, 'toggle-class-one');
    this.toggleClass(this.someElementTwo, 'toggle-class-two');
    this.toggleClass(this.someElementThree, 'toggle-class-three');
  }

  toggleClass(elementRef: ElementRef, className: string) {
    elementRef.nativeElement.classList.toggle(className);
  }
}

You can check out a working example on Stackblitz here

Remember that for the classList API, you have access to both the add() and remove() methods to add or remove classes from specific elements.

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

Is there a way to pass (req.param) using an input field and a button instead of manually entering it into the URL bar?

I'm attempting to collect input from the user and send it to the URL they specify. By combining it with url = "http://localhost:3000/"+":userInput" First, I attempted to gather user input and create a link using DOM methods <script> function m ...

Identify the descendant of the `<li>` tag

I need help creating a interactive checklist. The idea is that when you click on an item in the list, a hidden child element should become visible. <div id="list_one"> <h2>LIST TITLE</h2> <div id="line"></div> < ...

"Learn how to implement a feature that allows for the acceptance of string input in discord

I am struggling to find the right solution for my issue. I am trying to implement a change_nick command but unsure about what type/number option to utilize. This is how I'm creating my command: commands.create ( { ...

What is the most effective method to implement an isLoggedIn function in AngularJS that is accessible from any controller or template?

I'm looking to create an isLoggedIn() function that can be accessed by both controllers and templates. Templates need this function to execute something like ng-show="isLoggedIn()". What would be the most efficient way to achieve this? If using a ser ...

When adding elements to an array from a `for` loop containing a while loop, the new values replace the existing elements in the array

Whenever I add elements to an array from a while loop nested inside a for loop, it ends up replacing the previous elements in the array. var startDate = new Date(theoreticalData[0].UpdateDateMDY); var newDate = startDa ...

Enhance the appearance of a tree node by applying style to the "li" element

Here is a tree structure that I am working with - http://jsfiddle.net/anirbankundu/wzEBW/ This tree may contain any number of nodes. The requirement is that when a user hovers over a single node, the background color of the node should change. This can be ...

How can I substitute specific words in a string with multiple words from an array?

I'm faced with a challenge where I need to replace asterisks (*) in a sentence with words from an array. Let's take an example: let sentence = 'My * is * years old.'; let words = ['dog', 3]; //expected result => My dog is ...

A guide on dynamically integrating CKEditor into Vue.js 3, exclusively for the client side

I am facing a challenge with integrating CKEditor 5 into my Vue.js 3 application, particularly in ensuring that it is only loaded on the client-side. Due to server-side rendering limitations, I need CKEditor to be included dynamically based on the browser ...

What is the method to retrieve the character set of response data in an Ajax request?

Ajax Request: $("button").click(function(){ $.ajax({url: "demo.html", success: function(result){ $("#div1").html(result); }}); }); In this code snippet, an Ajax request is made to fetch data from the demo.html file. The response data is s ...

The precise moment for the formation as opposed to the choice of elements

To enhance the appearance of YouTube/Vimeo videos, I am utilizing a technique mentioned in this discussion, which involves creating custom thumbnails for embedded videos. The process is quite straightforward - displaying an image as a placeholder and repl ...

Tips for preventing the appearance of a horizontal scroll bar when utilizing the FlexLayoutModule in Angular

import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-property-feed', templateUrl: './property-feed.component.html', styleUrls: ['./property-feed.component.scss'] }) export class Prope ...

Terminating a client connection in Node.js using socket.io

What is the best way to terminate the socket connection on the client side? I am currently utilizing: socket.io 0.9 node.js 0.10.15 express 3.3.4 For example, when calling localhost/test -- server side var test = io .of('/test') .on(&apos ...

The bootstrap modal display issue: black background visible

In my HTML file, there are two modal dialogs that seem to be causing an issue. Interestingly, whichever modal dialog is placed first in the sequence of the HTML code displays properly when the button is clicked (and vice versa). Both modal dialogs have u ...

The type 'Observable' does not contain the properties found in type 'User'

I am trying to retrieve user data from Firestore, but encountering an error The type 'Observable' is missing the following properties from type 'User': email, emailVerified, uidts(2739) user.service.ts import { Injectable } from &apo ...

How to properly cast interfaces when using Angular 4's HttpClient to fetch items

Here is the layout of my interface interface IPlacesResult { summary: { queryTime: number; // ... }; results: { id: string; // ... address: { streetNumber: number; // ... }; }[]; } To populate this interface, I ...

Testing React components with Jest by mocking unnecessary components

Consider a scenario where we have the Page component defined as: const Page = () => <> <Topbar /> <Drawer /> <Content /> </> When writing an integration test to check interactions within the Drawer and Con ...

Choosing versatility over specificity when dealing with web API routes

Hey there! I'm a beginner when it comes to web API routes and I've encountered an issue where my call is choosing the more general route instead of the specific one. The AJAX call I am using is: $.getJSON("/api/solutions/GetSolutionByCategory ...

Angular continually monitors changes for dom-to-image and generates countless renders

I am trying to implement a feature in my Angular 4 application where child-components render wallpapers for themselves using dom-to-image-more. The issue arises when I try to dynamically render these child-components using *ngFor. The parent component h ...

Discover the identity of an element through the value of another element

Looking for a way to retrieve the id value based on the input value in this HTML code. For instance, I need to identify the id value associated with the input value of number2 - which is unknown2. How can this be achieved using jQuery? <th id="unknow ...

Is there a way to determine if a button was clicked using twig?

I need assistance with implementing a button in my twig file within a table that will remove an element from an array. Ideally, I would like to remove the element based on its index. From the research I have conducted, it seems that data manipulation shou ...