Using Angular 2 to Bind a Single Click Event to Multiple Elements

Within the component's export class, I have defined iconCheck: string;. In the constructor, I set this.iconCheck = "add_circle";. Additionally, in the export class, I have the following method:

iconChange() {
    if(this.iconCheck == "add_circle") {
      this.iconCheck = "remove_circle"
    } else {
      this.iconCheck = "add_circle";
    }
  }

My HTML contains multiple collapsible/expandable elements using Bootstrap accordions. Each element has a toggle icon (+/-) that should change when clicked. However, the issue is that when one accordion is clicked, all other accordions' icons also change. I am looking for a way to bind the click event to only the specific element that was clicked. Essentially, I need a scope limit or a way to isolate the click event to just the individual element that triggered it.

<a data-toggle="collapse" (click)="iconChange()" href="#collapse1">
 Property 1 
 <i class="material-icons pull-right">{{iconCheck}}</i>
</a> 

<a data-toggle="collapse" (click)="iconChange()" href="#collapse2">
 Property 2 
 <i class="material-icons pull-right">{{iconCheck}}</i>
</a>

Answer №1

There have been instances where I faced this issue before. My go-to solution is to use an index to monitor which accordion the user has clicked on, and then utilize that information to toggle icons accordingly.

I've put together a straightforward Plunker demo. Take a look and see if it meets your requirements :)

app.ts:

export class App {
  name:string;

  selectedIndex: number;

  constructor() {
    this.name = `Angular! v${VERSION.full}`;
    this.selectedIndex = -1;
  }

  iconChange(index: number){
    if(this.selectedIndex == index){
      this.selectedIndex = -1;
    }
    else{
      this.selectedIndex = index;
    }

  }
}

Template:

<div>
  <h2>Hello {{name}}</h2>
  <div class="div1" (click)="iconChange(1)" >
    Hi 
      <i class="fa" [ngClass]="{'fa-plus': selectedIndex != 1, 'fa-minus': selectedIndex == 1}" aria-hidden="true" style="float: right"></i>
    </div>
  <div class="div2" (click)="iconChange(2)">
    Hi again!
      <i class="fa" [ngClass]="{'fa-plus': selectedIndex != 2, 'fa-minus': selectedIndex == 2}"  aria-hidden="true" style="float: right"></i>
  </div>
  <div class="div3" (click)="iconChange(3)">
    Bye!
      <i class="fa" [ngClass]="{'fa-plus': selectedIndex != 3, 'fa-minus': selectedIndex == 3}"  aria-hidden="true" style="float: right"></i>
  </div>
</div>

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

The error message "@graphql-eslint/eslint-plugin: problem with the "parserOptions.schema" configuration"

Our team is currently working on developing micro-services using NestJS with Typescript. Each of these services exposes a GraphQL schema, and to combine them into a single graph, we are utilizing a federation service built with NestJS as well. I recently ...

Tips for upgrading from AngularJS 1.8.x to Angular CLI version 11.2.3

Looking for a straightforward way to update the angular version for my web app. Any suggestions on how to go about this? ...

Angular error: Attempting to create a property on an empty string using Rxjs

Currently, I am working with Angular 11 and using rxjs. I am trying to filter my course collection to show only courses with the category "frontend," but I am encountering some errors. Here is my code: getPosts():Observable<ICourses[]> { return ...

Utilizing the validator in Vue with the setup script, TypeScript, and the composition API

While working on some code from a tutorial, I came across the challenge of implementing a validator in a similar fashion to the example provided. My task involves utilizing the script setup, typescript, and the composition API. props: { image: { ...

The FileSaver application generates a unique file with content that diverges from the original document

I'm attempting to utilize the Blob function to generate a file from information transmitted via a server call, encoded in base64. The initial file is an Excel spreadsheet with a length of 5,507 bytes. After applying base64 encoding (including newlines ...

What is the best way to create a function that can securely search for a URL containing parameters while ensuring type safety?

I am working on a NextJS/React application. We have a large object containing internal URLs, each with a createPath function that looks similar to this: const URLS = { dashboard: { createPath: ({ accountNumber }: { accountNumber: string }) => ...

Prevent the element attribute from being enabled before the onclick function is triggered

I am attempting to implement a feature in Angular that prevents double clicking on buttons using directives. Below is the pertinent code snippet from my template: <button (click)="onClickFunction()" appPreventDoubleClick>Add</button> And her ...

Updating an existing Observable asynchronously using the pipe method

My scenario involves working with an Observable that is subscribed to via the async-pipe. <ng-container *ngIf="invitations$ | async as invitations"> I initialize this Observable in the ngOnInit function: this.invitations$ = this.getInvitat ...

Utilizing Angular 2 alongside ngrx/store for seamless updates to specific properties within the state object without disrupting the entire structure

I am facing an issue where I need to update a property of a state object without creating a new object. Is there a way to add or update a single property without replacing the entire object? Below is the reducer code: const initialState = { all: [], ...

Guide on creating frozen columns in an Angular 2 table with the ability to scroll through multiple columns

Within my table, there are 3 columns that must always remain on the left side. Additionally, there is a column containing a grid where each element represents an hour of the day, requiring it to be scrollable. I have attempted various proposed solutions, ...

Following a successful compilation, the Angular application displays an empty page

Alert: Uncaught TypeError: Cannot read property 'length' of undefined at Object./src/components/Carousel.vue (Carousel.vue:123) at __webpack_require__ (bootstrap:1024) at Module../src/main.js (main.js:1) at __webpack_require__ (b ...

Oops! Looks like an issue has popped up: using require() of an ES module is not supported when using recharts in combination with next.js

I've noticed some similar questions, but none of them seem to address my particular issue. I'm currently working on a webapp using next.js (with typescript). Within the app, I am utilizing recharts, however, I am encountering a compilation error: ...

What does it signify when it is stated that "it is not a descendant of the indexer"?

Currently, I am diving into Typescript with the help of this informative guide on indexer types. There is a specific piece of code that has me puzzled: interface NumberDictionary { [index: string]: number; length: number; // okay, length shoul ...

Angular 9 Singleton Service Issue: Not Functioning as Expected

I have implemented a singleton service to manage shared data in my Angular application. The code for the service can be seen below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataS ...

Disabling `no-dupe-keys` in ESLint does not seem to be effective

Currently, I am working on a project where I have incorporated Typescript and ESLint. However, I have encountered an issue with the error message stating: An object literal cannot have multiple properties with the same name. I am looking to disable this s ...

Show values in an angular template using an array

I want to showcase values of an array using *ngFor const blockData = [ {text: sampleText1, array: [val1]}, {text: sampleText2, array: [val2, dat2]}, {text: sampleText3, array: [val3, dat3]} ] <div *ngFor="let data of blockData"> ...

Is it possible to utilize the spread operator for combining arrays?

Consider two different arrays represented by variables a and b. The variable c represents the output as a single array, indicating that this method combines two or more arrays into one. let a=[a ,b]; let b=[c ,d]; c=[a,...b] The resulting array will be: ...

What is the appropriate interface for determining NavLink isActive status?

In the process of crafting a "dumb" component using NavLink, I am defining the props interface for this component. However, I encountered an issue when trying to include isActive in the interface. It's throwing errors. I need guidance on how to prope ...

When using react-admin with TypeScript, it is not possible to treat a namespace as a type

Encountering issues while adding files from the react-admin example demo, facing some errors: 'Cannot use namespace 'FilterProps' as a type.' Snippet of code: https://github.com/marmelab/react-admin/blob/master/examples/demo/src/orde ...

Getting the Full Error Message in Axios with React Native Expo

I'm encountering a network error while using Axios with React Native. Previously, when working with React JS on the web, I could console log the error or response and see all the details. However, in Expo, all I get is "Axios error: Network error" wh ...