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

Adding a new data source to Mapbox

When working with mapbox, I encountered a 404 error while trying to load a layer from a variable geojson. The addSource data function always expects the data to be a URL. Is there a way to use variables instead? this.map.on('load', () => { c ...

In Angular 2, property binding will not function properly when attempting to bind to an object

I have encountered a strange issue with Angular 2 property binding. Let's start with the Store class: export class Store { id: number; name: string; address: string; } This is the component code snippet: export class MyBuggyComponent i ...

Issue encountered while developing custom Vuejs + Typescript plugin

In my index.ts and service plugin files, I have this structure: https://i.sstatic.net/Oh3Gq.png service.ts declare interface Params { title: string; description?: string; type?: string; duration?: number; } export default class ServiceToast { ...

Input does not have access to ngModel's property

I'm facing an issue with NgModel as it doesn't seem to work when I try to save data from an input field. Uncaught Error: Template parse errors: Can't bind to 'NgModel' since it isn't a known property of 'input'. (" ...

Can the ElasticSearch standard Node client be considered secure for integration with cloud functions?

When working with my Typescript cloud functions on GCP, I have been making direct HTTP requests to an ElasticSearch node. However, as my project expands, I am considering switching to the official '@elastic/elasticsearch' package for added conven ...

Discovering the specific p-checkbox in Angular where an event takes place

Is there a way to assign an ID to my checkbox element and retrieve it in my .ts file when the checkbox is selected? I want to pass this ID along with the true or false value that indicates if the checkbox is checked. Here's an example code snippet: &l ...

The 'firestore' property is not found within the 'Firebase' type

I'm currently working on retrieving the precise time a document is generated. To achieve this task, I have included the following imports: import { Firebase } from '@ionic-native/firebase/ngx'; import { AngularFirestore } from '@angul ...

Issue with React not displaying JSX when onClick Button is triggered

I've recently started learning React and I'm facing a problem that I can't seem to figure out. I have a basic button, and when it's clicked, I want to add another text or HTML element. While the console log statement is working fine, th ...

What is the proper way to bind data next to a string in Angular?

I am facing an issue with two variables that are supposed to form a link for an image. I have tried putting them in the src tag using the following code snippet: [src] = {{part1}}+"_"+{{part2}} However, this approach is not working as expected. The scr ...

What could be causing Typescript to inaccurately infer the type of an array element?

My issue revolves around the object named RollingStockSelectorParams, which includes arrays. I am attempting to have TypeScript automatically determine the type of elements within the specified array additionalRsParams[title]. The main question: why does ...

Creating and updating a TypeScript definition file for my React component library built with TypeScript

As I work on developing a React library using TypeScript, it is important to me that consumers of the library have access to a TypeScript definition file. How can I ensure that the TypeScript definition file always accurately reflects and matches the Java ...

React did not allow the duplicate image to be uploaded again

I've implemented a piece of code allowing users to upload images to the react-easy-crop package. There's also an "x" button that enables them to remove the image and upload another one. However, I'm currently facing an issue where users are ...

Modify the selection in one dropdown menu based on the selection in another dropdown menu using Angular 8

When I have two dropdowns, I aim to update the second dropdown with a matching JSON object based on the value selected in the first dropdown. JSON this.dropdownValues = { "mysql 8": { "flavor": [ "medium", ...

Create the correct structure for an AWS S3 bucket

My list consists of paths or locations that mirror the contents found in an AWS S3 bucket: const keysS3 = [ 'platform-tests/', 'platform-tests/datasets/', 'platform-tests/datasets/ra ...

The inline style in Angular 2 is not functioning as expected when set dynamically

Having a small dilemma... I'm trying to apply an inline style within a div like this: div style="background: url(..{{config.general.image}})"></div Oddly enough, it was functioning in beta 16 but ever since the RC1 upgrade, it's no longer ...

The error message "Property '$store' is not defined on type 'ComponentPublicInstance' when using Vuex 4 with TypeScript" indicates that the property '$store' is not recognized

I'm currently working on a project that involves using TypeScript and Vue with Vuex. I've encountered an error in VSCode that says: Property '$store' does not exist on type 'ComponentPublicInstance<{}, {}, {}, { errors(): any; } ...

Generate sample data within a fixture

Currently, I am in the process of working on a project that involves creating users and conducting tests on those users. To generate user data such as first name and last name, I am utilizing the faker tool. My goal is to create a user with these generated ...

Tips for enlarging the font size of a number as the number increases

Utilizing the react-countup library to animate counting up to a specific value. When a user clicks a button, the generated value is 9.57, and through react-counter, it visually increments from 1.00 to 9.57 over time. Here's the code snippet: const { ...

I built a custom Angular application integrated with Firebase, and I'm looking for a way to allow every user to have their individual table for managing tasks

I am looking to enhance my code so that each user who is logged in has their own tasks table, which they can update and delete. Additionally, I need guidance on how to hide menu items tasks, add-tasks, logout for users who are not logged in, and display th ...

Creating a React component with a column allowing multiple checkbox selections in NextUI table

Setting up multiple "checkbox" columns in a table using the NextUI table has been my current challenge. Each row should have selectable checkboxes, and I want these selections to be remembered when navigating between pages, running searches, or removing co ...