Binding events or the DOM within an ngFor loop in Angular 2

How can we efficiently toggle the visibility of a div inside ngFor, as shown in the example below? Each click should toggle the visibility of a div from the same iteration. The main concern is how to properly bind this event/DOM.

<div *ngFor="let hero of heroes; let i = index">
  <div [hidden]="?">Toggle my visibility</div>
  <div (click)="?">Click me</div>
</div>

Answer №1

In my opinion, a great solution would be to establish a new array that holds visibility attributes for each hero. Therefore, we can create an array (where each hero is initially visible):

this.heroesVisibility = new Array(this.heroes.length).fill(true);

In the component class, we can implement the following function:

public toggleVisibility(id : number) : void {
    this.heroesVisibility = !this.heroesVisibility;
}

Then, in the template:

<div *ngFor="let hero of heroes; let i = index">
  <div [hidden]="!heroesVisibility[i]">Toggle my visibility</div>
  <div (click)="toggleVisibility(i)">Click me</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

Leveraging jQuery template for JSON visualization

I've been struggling for days to understand how to render JSON data using jQuery templates with no luck. I was hoping someone could help me figure out where I'm making a mistake. The JSON data I am working with looks something like this: [{"pk" ...

The getJSON function encountered an error due to an unexpected token ":"

I have reviewed many similar questions and answers, but I am still struggling to solve my specific issue. Here is the code snippet in question: $.getJSON("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + results[0].geometry.location.lat() + ", ...

How can I generate spheres in threejs with varying radii while all passing through the shared point located at coordinates (0,0,200)?

Is there a way to generate spheres in threejs where the radius increases while always passing through a single point at 0,0,200? This would allow the origin of each new sphere to move along the z-axis. Appreciate any help, AriemWebgl ...

"Utilizing the jQuery ID selector along with the validation capabilities of

Recently, I stumbled upon some code I wrote a few days back, and surprisingly, it's working flawlessly, although I can't quite figure out how. I'm reaching out to see if anyone could shed some light on this for me. Within my validation code ...

Refreshing information in two view models using Ajax

I am currently working on an application that utilizes two viewmodels. One is responsible for rendering a form, while the other displays a table of form data. My issue lies in reloading the form after it has been successfully saved via an Ajax call. Even ...

Using TypeScript with Angular-UI Modals

Currently, my goal is to create a modal using angular-ui-bootstrap combined with typescript. To begin, I referenced an example from this link (which originally utilizes jQuery) and proceeded to convert the jQuery code into typescript classes. After succes ...

Tips for displaying a notification after a successful form submission using jQuery and AJAX

While attempting to submit a PHP form using jquery $.ajax();, I have encountered a peculiar issue. The form is successfully submitted, however, when I try to display an alert message - alert(SUCCESS); on success, it does not work as expected. Any ideas on ...

406 Not Acceptable Error: Ajax and Rails don't mix well

I'm facing a challenge in getting this request to go through ajax without triggering a 406 error. My goal is to use ajax to add an item to a cart, which does happen successfully, and the cart gets updated after a refresh. However, all I'm getting ...

Various endpoints to consider when conducting end-to-end testing with Protractor

What is the best way to execute end-to-end test cases for Protractor in an Angular workspace with multiple applications? For instance, consider the following structure: -/angularRootFolder -apps -First app -e2e -pageobjects ...

What is the best way to send a prop to my home route following a redirect?

I am working with react-router-dom and I want to pass :id to my first route (/) when redirecting. This is important so that I can access :id in my Interface component and maintain consistent URL structure for my single-page application. Is it feasible to a ...

Verify if a section of an arc intersects with a circular shape

I'm currently working on determining the intersection between an arc and a circle. I have successfully identified intersections when I treat the arc as a complete circle using the code snippet provided. However, I am facing difficulty in finding a so ...

Verify if the nested arrays within the object consist of any empty elements

Take a look at the object below: { "params": { "time_to_diagnosis": [ { "field": "date_of_diagnosis", "value": "" }, { "field": "date_of_symptom_onset", "value": "2019-09-01" } ], "time ...

Sending information using AJAX to interact with a PHP script

My input field is set up to receive multiple files: <input id="propertyImages" type="file" name="submission_img[]" multiple accept=".jpg, .jpeg, .png, .gif"/> Afterwards, I send this data via JS/Ajax to a PHP file: //Creating the form data to be s ...

Which one is more suitable for optimizing my effect - useCallback or useMemo?

When a user hovers on a button, the following tooltip will trigger an API call. I'm unsure whether I should use useCallback or useMemo to optimize this process and prevent unnecessary API calls. I find it challenging to determine the appropriate use c ...

Integrating Stripe Checkout with Angular and node.js for seamless payment facilitation between third-party payers and receivers

After spending several days on this issue, I am still struggling to find a viable solution. My goal is to utilize my account (via public and private keys) to facilitate payments from one account to another, without any funds passing through my own account. ...

Alter the active nav-item's color using Reactjs

Is there a way to dynamically change the color of the navbar text based on the page being browsed? Check out this sample code For instance, when on the homepage, I'd like the home icon to appear in blue. https://i.sstatic.net/uTfwP.png Take a look ...

Error TS2532 in Typescript is indicating that an object may potentially be undefined, despite the fact that I have applied necessary checks

Can anyone help me with this strange issue I'm experiencing in Typescript? I keep getting an error about a potential undefined value: https://i.sstatic.net/GaLv7.png if (!flatListRef || !flatListRef.current) return flatListRef.current.someMethod() ...

What are the steps to resolve the "Rename this file" code smell issue found in the _app.js file of a Next.js project using Sonarqube?

When I used npx create-next-app to build a sample Next.js application, a code smell popped up during the sonarqube scan. The issue pointed out was that the default export names and file names do not match. However, in this case, the _app.js file is integra ...

"Even after firing the observable through an event, the Async pipe continues to return null

I am currently working with an angular component that incorporates a rich text editor (tiptap v2) and displays the corresponding JSON output. I have created an observable from the update event provided by the editor, aiming to initialize the editor with mo ...

What causes the "Cannot read properties of undefined" error in Vue when an array is initialized and output is still being displayed?

I am working with two vue files, namely App.vue and a component called UsersPage.vue. UsersPage.vue: <script> export default { data:() =>({ usersList : [] }), methods:{ async createUsersList(){ this.usersLi ...