Angular2: Leveraging click events to manage CSS classes on elements

I am currently developing a web app using Angular 2. I'm facing an issue where the active element should receive an extra CSS class when clicked, but adding the ":active" CSS attribute with a custom class doesn't work as expected. The ":focus" property also doesn't seem to be working properly. I've tried using Angular 2 directives like Ng-click, ng-switch, ng-if, and ng-class to no avail.

Here's the code snippet so far:

<footer>
<div class="thumbnail-slider">
    <div class="thumbnail-img-container">
        <img class="thumbnail-slider-img" (click)="getActualImage(url)" 
            *ngFor="let url of urls" [src]="url"/>
    </div>
</div>
</footer>

The component code:

import { Component, NgModule, Input, Output, ViewChild, EventEmitter, ElementRef, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
import { BrowserModule, DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Http, Response, ResponseContentType } from '@angular/http';

ReqConstImages } from '../../services';
import { Subscription } from 'rxjs/Subscription';
import { Subject } from 'rxjs/Subject';
import { ObservableUtility } from '../../helper/index';
import { trigger, state, style, transition, animate } from '@angular/animations';


let css: any = require('!raw-loader!less-loader!./thumbnail-slider.less');

@Component({
  selector: 'thumbnail-slider',
  templateUrl: 'thumbnail-slider.html',
  styleUrls: [css],
  animations: [
  trigger('click', [
    state('inactive', style({
      border: '5px yellow solid'
    })),
    state('active',   style({
      border: '6px green solid'
    }))
  ])
]

})

export class ThumbnailSliderComponent implements OnInit, AfterViewInit, OnDestroy {


  constructor(private http: Http, private sanitizer: DomSanitizer, private observableUtility: ObservableUtility) { };




}

It may not seem like a major issue, but I haven't been able to find the right solution yet. Any tips or guidance on how to add an additional CSS class to the clicked element in Angular 2 would be greatly appreciated!

Answer №1

To update the styling of an element on click, try defining a new variable in your component typescript file. Modify the value within the clicked function and then apply it to the class attribute.

For example: *.ts

public updatedClass = "class1";

onClickedItem(){
    this.updatedClass = "class2";
}

*.html (Template)

<div class="{{updatedClass}}" (click)="onClickedItem()"></div>

This code snippet allows you to dynamically change the class of an element when it is clicked.

Answer №2

If you're looking for a solution, consider implementing something similar to the example below. Create a variable called selectedUrl to hold the URL that is clicked on, then compare it with each image in the iteration to determine if the class should be set to active.

  <img 
       class="thumbnail-slider-img" 
       *ngFor="let url of urls"
       [src]="url"
       (click)="selectedUrl=url"
       [class.active]="selectedUrl === url"/>

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

What is the default delay when utilizing the $timeout function in AngularJS?

While looking at the concise information on the AngularJS $timeout documentation page, I noticed that the 'delay' argument is listed as optional. However, when utilizing $timeout without specifying a delay, I observed that a delay is still implem ...

Incorporate a fresh attribute to the JSON data in an Angular API response

I'm currently working on updating my JSON response by adding a new object property. Below is an example of my initial JSON response: { "products": [{ "id": 1, "name": "xyz" }] } My goal is to include a new object property ca ...

Problem with transitions not working properly in Vue.js.The issue

Experiencing an issue with the Vue.js transition feature. Check out this link for reference. When the transition enters, it works smoothly, but when transitioning out, it's not functioning properly. File: genetic.vue <transition name="slide-f ...

In what way does the map assign the new value in this scenario?

I have an array named this.list and the goal is to iterate over its items and assign new values to them: this.list = this.list.map(item => { if (item.id === target.id) { item.dataX = parseFloat(target.getAttribute('data-x')) item.da ...

How to Load JavaScript Files into Joomla 2.5 default.php File

When creating a component in Joomla 2.5, I encountered an issue while trying to add some JavaScript code into the layout file tmpl/default.php . To include the JavaScript files, I used the following code: $document->addScript(JURI::base() . "components ...

When navigating back in Next.js, the URL changes but the content remains the same

I'm currently troubleshooting an issue where the content is not updating when I navigate back using the browser's back button or by setting a button with router.back. The URL updates correctly, but the content remains the same. When I refresh the ...

Transform the text area in preparation for a GET request

Trying to figure out how to pass the text from a textarea into the source attribute of an image tag while retaining all formatting, including line breaks. After some research, it seems that the best way to accomplish this is by base 64 encoding the text a ...

Toggling the visibility of a div using JavaScript

When I click the button, I want to show and then hide a div. However, it doesn't work on the first click - only on the second click. How can I make it work on the first click? HTML <p>Click the button</p> <button onclick="myFu ...

An error has occurred in Angular: No routes were found that match the URL segment 'null'

I've recently developed a simple Angular page that extracts an ID (a guid) from the URL and uses it to make an API call. While I have successfully implemented similar pages in the past without any issues, this particular one is presenting challenges w ...

Excessive Empty Area beneath <td>

I'm currently working on creating an e-book and I have encountered a concerning issue. The <figure> and <figcaption> elements are appearing as unknown tags in Sigil. To work around this problem, I decided to use a <table> for display ...

The attempt to convert an array into an array of objects using the map function was

var array = ["x","y","z"] array.map(object => {object.key: object}) I thought array would transform into [{key:"x"},{key:"y"},{key:"z"}] but I encountered an error at object.key in my map function. Where did I go wrong? ...

Executing an ajax post when a user clicks on a link or button

<tr> <td> <span id="id_1"> <a href="/Path" >Name</a> <a href="#">Delete</a> </span> </td> &l ...

How can I locate the input field using XPath that is positioned next to a

I am having difficulty targeting a checkbox located next to a label with a specific name that includes an underscore character. Here is an example of the DOM structure: <div id="form-2143"> <div id="wrap-1353"> <label id="numberfield ...

Page for users to login using React

Struggling to create a login page in React due to the asynchronous nature of setState. Upon submission, the state is not updating with form values, only displaying old initial values. How can I ensure that the submit function receives the new values? Is ...

When using Node.js, you may encounter the error message: "TypeError: brevo.ApiClient is not a constructor

My goal is to set up an automatic email sending system that, upon receiving details like name and email, will send a confirmation email to the provided email address with the message "subscribed." I've been working on this task for about 7 hours strai ...

Schematic tool for updating ViewChild in Angular 8 upgrade

Currently, I am in the process of following a guide to upgrade an Angular project to Angular 8. In order to complete this upgrade, it has been highlighted that it is now necessary to specify when ViewChild should be initialized using the static variable as ...

The variable X has been defined, but it's never actually utilized. Despite declaring it, I have not accessed its

I have encountered warnings in VSCode while using certain properties in my Angular component. The warnings state: '_id' is declared but its value is never read.ts(6133) (property) ItemEditComponent._id: number | undefined '_isModeEdit' ...

Assertion using Node.js with Selenium WebDriver

I am currently working on implementing assertions for testing using selenium webdriver with node js. However, I am encountering an issue where it returns undefined when trying to assert the page title (which is the URL of the page). It seems like I may n ...

What is the best way to send the selected option from a dropdown to a button click function within the controller?

I need to pass the selected value from a user's country selection dropdown to the ng-click="saveChanges()" function on the submit button. Is there a correct method for achieving this? I want to be able to access the user's selection from the dro ...

The elements within the array are being refreshed accurately, however, a separate component is being removed

I have developed a component that has the ability to contain multiple Value components. Users can add as many values as they want, with the first value being mandatory and non-removable. When adding two new Value components, I provide input fields for name ...