Issue with toggleClass() function when using Angular 4

My code includes the addition of jQuery in the script using

 import * as $ from 'jquery';   

and also adding jQuery in the HTML file. However, the toggleClass() function is not functioning correctly. Upon checking the console, there were no errors displayed, it was completely empty.

Displayed below are my HTML and ts code:

HTML Code:

 <div class="web" (click) = "myFunc()">
    <p>
        Web Development&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
       $300
    </p>
 </div>

 // Additional div elements

</div>
<div class="total">
   Total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   $0
</div>

ts Code:

import { Component } from '@angular/core';
import * as $ from 'jquery';

// Angular component configuration

export class AppComponent {
  myFunc() {
    $(this).toggleClass("active");
  }
}

Answer №1

Avoid using jquery, simply update your click binding on view to (click)="myFunc($event)", and inside the function myFunc, make the following changes:

myFunc(e) {
    const element: HTMLElement = e.target;
    element.classList.toggle('active');
}

Answer №2

If your code is not functioning as expected, it could be due to the fact that $(this) is pointing to the current class instance.

In order for your jQuery code to work correctly, you should reference the source element within the jquery. You can achieve this by passing the '$event' object to your function from the template and then accessing the target object inside the function:

<div class="web" (click)="myFunc($event)">

myFunc(event: any) {
  $(event.target).toggleClass("active");
}

To see an example of this in action, check out this stackblitz link: https://stackblitz.com/edit/angular-dsely1

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

In the event that the hash consists of just one string, disregard any additional conditional statements

Currently, I am in the process of updating one of my coding playgrounds and facing some issues. If the user has only the "result" string in the hash like this... testhash.html#d81441bc3488494beef1ff548bbff6c2?result I want to display only the result ( ...

Printing the object name in CreateJS can be achieved by accessing the name property

var stage = new createjs.Stage("demoCanvas"); console.log(stage.constructor.name);//prints a <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script> <script src="https://code.createjs.com/createjs-2015.11.26.mi ...

Voxel world culling: The art of selection

In the realm of my imagination lies a world filled with voxels, measuring at 320*320*96 in size. My vision is to load this expansive world directly into the memory of my graphics card in order to avoid any loss in performance while transferring new "chunks ...

The create document feature seems to be malfunctioning for some reason. Any ideas why it's not working properly in Firebase with Angular

I've been attempting to submit user data to the Firebase Firestore database, but I'm experiencing issues with the function that is supposed to create a new collection. Despite trying different methods, none of them seem to be working for me. I ha ...

Revamp the HTML table with JavaScript headers

I imported data from a CSV file into an HTML table and here is how it appears: <div id="myTable" style="-ms-overflow-x: auto;"> <table> <tbody> <tr class="rownum-0"> <td>Make</td> ...

How can one quickly display a confirmation dialog box within react-admin?

Looking for a way to implement a confirmation dialog in my react-admin project, similar to JavaScript's alert function but more visually appealing. I want the user to only proceed with certain database operations if they click OK on the dialog. I cou ...

Next JS is trying to access a JSON file that does not exist

After setting up a route "/es/servicios" and configuring it in next.config.js: module.exports = { async redirects() { return [ { source: '/', destination: '/es', ...

How do I collapse the sidebar in mobile and tablet view using Bootstrap 4?

I am trying to create a collapsible sidebar that expands on large screens such as lg, but collapses with a visible button for tablet and mobile views (md or smaller). How can I achieve this responsive behavior for my sidebar on mobile and tablet views? It ...

Trigger the onsubmit function in an HTML form exclusively when the submit button is clicked

By clicking the plus icon, both submitFunc() and meanFunc() functions are currently executed. However, I want to modify it so that submitFunc() is only triggered when the Submit button is pressed. function submitFunc(e) { alert('submit') } ...

Developing bi-directional binding for newly generated elements post initial compilation

I have developed a directive that dynamically generates a form based on a JSON received from the server. I am trying to include the ng-model attribute in the input elements so that I can access the input values once the user enters them and clicks submit. ...

Implementing new updates to an object without affecting existing values in Vue.js 2

I am currently facing an issue with updating values for an object received in a payload before saving it to the database. Despite making changes, the new values are not being persisted correctly. I am utilizing Vue.js 2 for this task. How can I effectively ...

Angular2 - navigating through routes with different language preferences

Hello, I am interested in setting up routes with language included in the format below: www.domain.com/lang/sometimes For example: www.domain.com/en/sometimes www.domain.com/de/sometimes Is it feasible to create a route like this: RouterModule.forChil ...

Why is only the peak of the wave visible? I am eager to showcase the full extent of its beauty

Having an issue with the appearance of a superposed wave using threejs. When displayed, the wave made from plane material only shows the upper half, but when turned upside down using mouse dragging, it appears correctly. // Turn the wave plane upside down ...

Javascript deepmerge causes issues with objectid manipulation

While I have experience with javascript, using node.js for the first time has presented some challenges. I am attempting to form a basic query to be used in mongoose, with the intention of adding conditions later on. I am currently employing deepmerge to m ...

Retrieving values with Jquery on a function's onClick event

Here is a small script that retrieves values from a select element <script> jQuery(document).ready(function() { var selectedValue = jQuery("#tr_val").val(); }); </script> When you click on this div and execute the open_win function, I need t ...

issue encountered while attempting to install external packages using npm for Angular 4

I attempted to add angular2-datatable and loadash using npm install --save angular2-datatable and sudo npm i --save lodash However, I encountered this error message: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c2e392c ...

Using the after ship.com API with CORS in JavaScript using Ajax

Hi everyone, this is my first time posting here. I'm having trouble sending data via the POST method. When I checked the console, I saw the following error message: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote ...

Vertical Orientation in HTML

Would appreciate some assistance on creating a vertical text with HTML similar to the example in the linked screenshot. It needs to be straightforward and vertically oriented. Check out the screenshot for reference ...

A guide to strictly defining the subclass type of object values in TypeScript

How do I enforce strict subclass typing for object values in the SHAPE_PARAMS definition? When using type assertion like <CircleParameter>, missing properties are not caught by linting. Is there a way to define subclass types strictly? const Shapes ...

Error: The property 'ss' cannot be accessed because it is undefined

Our main source page will be index.html, while Employees.html is where our results end up. An error occurred: TypeError - Cannot read property 'ss' of undefined Error in the code: let rating = req.body.ss; Seeking assistance please >< C ...