Are multiple click events needed for identical buttons?

In my component, there is an HTML structure like this:

<div id="catalogo" class="container">
    <div class="row">
        <div *ngFor="let artista of artistas" class="col-sm" style="margin-top:20px">
            <div class="card border-dark text-center" style="width: 18rem;">
                <div class="card-header">
                    <h5>{{artista.name}}</h5>
                </div>
                <img src={{artista.img}} class="__card-img-top" alt="...">
                <div class="card-body">
                    <h6 class="mb-2">
                        {{artista.emoji}}
                    </h6>

                    <button (click)="onClick()" type="button" class="btn btn-info btn-sm mr-1 mb-1">
                        ℹ️ — Discografia
                    </button>
                    <div *ngIf="this.conteudoVisivel" class="__albumInfo">
                        <hr>
                        <p>{{artista.album[0]}}</p>
                        <p>{{artista.album[1]}}</p>
                        <p>{{artista.album[2]}}</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

Each instance of this component displays different information through text interpolation.

There seems to be a problem where clicking on one button affects all the cards instead of just its specific card.

https://i.stack.imgur.com/SE8MC.png

Although there are multiple buttons in the code, only one is visible in the HTML. How can I differentiate between the buttons and assign them individual click functionalities?

Answer №1

To achieve this, I suggest creating a map and utilizing the ngFor index. html:

<div
  *ngFor="let artist of artists; let i = index"
  class="col-sm"
  style="margin-top: 20px"
>
  <div class="card border-dark text-center" style="width: 18rem">
    <div class="card-header">
      <h5>{{artist.name}}</h5>
    </div>
    <img src="{{artist.img}}" class="__card-img-top" alt="..." />
    <div class="card-body">
      <h6 class="mb-2">{{artist.emoji}}</h6>

      <button
        (click)="onClick(i)"
        type="button"
        class="btn btn-info btn-sm mr-1 mb-1"
      >
        ℹ️ — Discography
      </button>
      <div *ngIf="this.visibleContentMap[i]" class="__albumInfo">
        <hr />
        <p>{{artist.album[0]}}</p>
        <p>{{artist.album[1]}}</p>
        <p>{{artist.album[2]}}</p>
      </div>
    </div>
  </div>
</div>

Component:

export class YourComponent {
  visibleContentMap = {};

  onClick(index: number){
   this.visibleContentMap[index] = !this.visibleContentMap[index];
  }
}

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

Guidelines for declaring types in variable definitions in Typescript

In Typescript, you have multiple options to define a boolean variable such as: let a = true; let b: boolean = true; Given that true is already a boolean value, is it still typical to explicitly declare the variable type (like shown for b)? If yes, does ...

Angular 6 Error: Unable to access property 'e4b7...f' as it is undefined

I'm encountering an issue while trying to initialize an object based on a TypeScript interface. Even though I am assigning a value, I still receive an error stating that the property is undefined. interface ITableData { domainObjectName: string; ...

In a specific Angular project, the forget password feature is experiencing issues with sending email links in the Chrome browser. Interestingly, this issue only occurs the first

I'm currently working on an Angular 6 application that has been deployed with the domain "www.mydomain.com/". All the routes are functioning properly, such as "www.mydomain.com/dashboard" and "www.mydomain.com/products". However, there is an issue w ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

When the back button is pressed on android, the navbar does not immediately refresh the active class

When using a webapp on Chrome for Android, pressing the back button results in double active items in the navbar. Clicking outside of the navbar removes the old active item. I attempted to resolve the issue by adding [routerLinkActiveOptions]="{ exact: tr ...

When using Typescript inheritance, the datatypes shown in IntelliSense are unexpectedly listed as "any" instead of

In my Typescript code, I have a small implementation where a class is either implementing an interface or extending another class. interface ITest { run(id: number): void } abstract class Test implements ITest { abstract run(id); } class TestEx ...

Using async method in controller with NestJS Interceptor

I am seeking a way to capture both the result and any potential errors from an asynchronous method within a controller using an interceptor. When an error is thrown, the interceptor can respond accordingly. However, I am struggling to figure out how to tri ...

Retrieving the unprocessed data from a Stripe webhook in Nest.js

I'm currently working on integrating a Stripe webhook request into my Nest.js application, and I need to access the raw body of the request. After referencing this example, I incorporated the following code snippet into the module containing a contro ...

Is it possible to separate a portion of HTML into a template and reuse it in multiple locations within a webpage?

In my HTML, I have an issue with duplicate code. In Java, I typically use IntelliJ to mark the code and select "extract method" => "replace 2 occurrences". I am looking for a similar solution in HTML, but the current method seems messy: <ng-template ...

sticky header on pinned tables in a React data grid

I have combined 3 tables together, with the middle table containing a minimum of 15 columns. This setup allows users to horizontally scroll through the additional columns conveniently. However, I am facing a challenge in implementing a sticky header featu ...

Managing errors when dealing with Observables that are being replayed and have a long lifespan

StackBlitz: https://stackblitz.com/edit/angular-ivy-s8mzka I've developed an Angular template that utilizes the `async` pipe to subscribe to an Observable. This Observable is generated by: Subscription to an NgRx Store Selector (which provides sele ...

Why does the method of type assigning vary between actual and generic types?

There are no errors in the code shown below: type C = {b: string}; class Class { data: C; constructor(data: C) { this.data = data; } test() { const hack: C & {a?: any} = this.data; //no error } } However, when a g ...

Issue encountered in Ionic/React/Typescript - Incorrect props supplied to React.FC<'erroneous props provided here'>

Having struggled with this issue for a while now without any success, I have searched through numerous questions here but none seem to address my specific case. Therefore, I kindly request your assistance. I am encountering difficulties passing props thro ...

An issue has occurred when attempting to import ES Module for setting all values to an object

Working on a project in Angular 6, I encountered an issue with using the npm package object-set-all-values-to version 3.9.45. Here's what I did: 1- Successfully installed it using npm i object-set-all-values-to ✔️ OK 2- However, when trying to i ...

Angular Dom does not update when invoking a function within a separate component

Greetings everyone! I am facing a situation where one component (let's name it recipe component) has a reference to another component (named grocery component). The method in my recipe component uses the reference to the grocery component to call a s ...

Two errors encountered in failing Jest test

Here is the test scenario that I am currently running: it('should return Notification Groups', (done) => { fetchAppNotifications('123', 'abc').subscribe((response) => { try { expect(response).toEqual(MOCK_FET ...

Combining Promises in Typescript to create a single Promise

Is there a way for me to return the temp_data object filled with data after using .map? Currently, it always returns undefined because I initialize temp_data as an empty object. But if I don't do this, I can't use LooseObject. Can anyone suggest ...

Can errors be selectively ignored in Angular's global error handler based on certain conditions?

I am currently facing a situation where I need to handle errors when calling an API to save data, either manually or automatically. For manual saves, I have implemented an Angular global error handler to display the error message if the save fails. Howeve ...

How can I implement a method to configure a 404 HTTP header in Angular 5 when a route is not found?

Is it possible to display a custom 404 header on the current page when there is no route matching my array? If not, could this potentially create SEO issues and have unknown pages indexed by search engines? ...

Incorporate an HTML code string into an Angular 2 template

I am working with HTML code stored in a Component variable, shown below: import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `Hi <div [innerHTML]="name"></div>`, styleUrls: [' ...