Discover the power of Angular2 by utilizing local template variables for efficient element management within a list

Here is a simple code snippet:

<ul>
  <li *ngFor="let item of list">
    <div class="button">Click to show text</div>
    <div class="text">hello</div
  </li>
</ul>

The goal is to create and assign a local variable called isVisible to each "hello" div so that when the .button element is clicked, only the corresponding text will be shown. I attempted to achieve this using the following code:

<ul>
  <li *ngFor="let item of list">
    <div class="button" (click)="isVisible ? isVisible = false : isVisible = true">Click to show text</div>
    <div *ngIf="isVisible" class="text">hello</div
  </li>
</ul>

However, clicking on the .button causes every .text div to be displayed. Is there a correct alternative method for achieving the desired behavior?

I am aware that one solution involves assigning an additional boolean variable (isVisible) to each item before displaying it, but I am exploring other approaches at the moment.

Answer №1

To display multiple items at once instead of just one, you can set a property on the objects being iterated over:

<ul>
  <li *ngFor="let item of list">
    <div class="button" (click)="item.isVisible ? item.isVisible = false : item.isVisible = true">Click to show text</div>
    <div *ngIf="item.isVisible" class="text">hello</div
  </li>
</ul>

The downside is adding a new property to your objects which may not be ideal. Creating a new component to handle this logic could be a more comprehensive approach, although it might be excessive depending on the context.

Answer №2

To avoid using a temporary variable in the HTML code, it is recommended to create a variable in the component itself. For example, you could have a variable like currentItemIndex in the component:

@Component()
export class AnotherComponent {
    currentItemIndex: number;
    onClick(index) {
        this.currentItemIndex = index;
    }
}

Then, in the component's HTML file:

<ul>
  <li *ngFor="let item of itemList; let i = index">
   <div class="btn" (click)="onClick(i)">Click to display text</div>
    <div *ngIf="currentItemIndex === i" class="txt">hello there!</div>
  </li>
</ul>

I hope this solution proves useful.

Answer №3

<li *ngFor="let item of list; let j = index">
 <div class="btn" (click)="setIndex(j); isDisplayed=!isDisplayed">Tap to reveal 
  content</div>
 <div *ngIf="isDisplayed && (currentPointer === j)" class="content">hi there!</div
</li>

and in your controller

setIndex(pos){
   this.currentPointer = pos;
}

Answer №4

If you want to streamline your code, consider creating a customized component to handle click events.

This new component can include an @Input variable that receives the item from ngIf and manages all necessary actions.

<ul>
  <li *ngIf="let item of list">
   <custom_component [item]="item"></custom_component>
  </li>
</ul>

Here is the template for the custom component:

<div class="button" (click)="isVisible ? isVisible = false : isVisible = true">Click to reveal text</div>
<div *ngIf="isVisible" class="text">Hello there!</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

Setting up the Leaflet routing feature on an Ionic 2 app

Recently, I set up a basic Ionic 2 project that integrates leaflet with the help of this repository: https://github.com/SBejga/ionic2-map-leaflet. Following that, I ran the command: sudo npm install --save leaflet-routing-machine to add leaflet routing m ...

Angular 8: ngx-socket-io changes the connection URL while in production mode

One issue arises when running the application in production mode. In development mode, the socket client successfully connects to http://localhost:3002/socket.io/?EIO=3&transport=polling&t=N4--_Ms. However, in production mode, the URL changes to ht ...

Creating Multiple Routes in a Single TypeScript and AngularJS Route File

I have built a module with TypeScript and AngularJS that includes multiple pages. I would like to use one TypeScript controller per page. How can I define multiple controllers in my routes? Currently, I have only defined one, but what if I have 6 or 7 co ...

Error occurs in Ionic 2 when attempting to make an Http request on a device, resulting in a net::ERR_CONNECTION

NOTE: For a detailed explanation, check out this Ionic Forum thread While the app functions perfectly when using ionic serve and is able to communicate over HTTPS with remote servers and the Google Maps API server through appropriate proxy settings, any r ...

The preview is not displaying in Chrome, specifically on Postman, due to a 500 error

I am currently working on an Angular 4 application with a .net core API. When I encounter an error 500, I am able to view the detailed error on Postman, but not in the Preview Tab of Chrome. Is there a way to display the error on Chrome Preview as well? W ...

Service B is receiving query parameters from Service A in a peculiar object format, leaving us puzzled as to the reason behind this unexpected structure

Issue: Encountered a strange bug when our service A (using laravel php) makes a call to an endpoint in service B (built with nodejs typescript + ajv + nestjs). Further explanation of the issue below. Below is an example of code in service A for constructi ...

Ways to activate a function onInit in Angular version 9

Currently, I have a function that is activated by clicking a button: export class ExhibitorDetailsComponent implements OnInit { @ViewChild(MapInfoWindow, { static: false }) infoWindow: MapInfoWindow openInfo(marker: MapMarker, content) { this.in ...

An issue arises with the Angular 7 application specifically on Mac clients when the production release is deployed

I am facing an issue with my Angular 7 application developed in Visual Studio. The application utilizes Entity Framework for data access. Strangely, everything works perfectly when I connect a Windows laptop or a MacBook Air (using Chrome or Safari) to the ...

What is the best way to create a function that requires an argument in TypeScript?

I'm looking to bring in a module that requires an argument in Typescript. This is how it looks in javascript: const cors = require('cors')({origin: true}); // JS What would be the equivalent syntax in Typescript? ...

Property 'text' is not found on type '{} | Response' in Angular/Node

After making changes to my angular project's package.json by downgrading from version 4.2.4 to 4.1.3 and then upgrading back to 4.2.4, I encountered an error while building the project: $ ng build Your global Angular CLI version (1.5.0) is greater ...

Deciphering TS2345: "The argument supplied, known as 'typeof MyComponent', cannot be assigned to the specified parameter type"

I am facing an issue while attempting to integrate a Typescript React component with react-onclickoutside. The error message that I encounter is as follows: TS2345: Argument of type 'typeof MyComponent' is not assignable to parameter of type &apo ...

JavaScript/TypeScript - Restricting to only assigned properties in an object

Consider this scenario: Suppose we have an object with the following properties: const objOne = { car: 'ford', location: 'Munich', driver: 'John' } and a second object that only contains some of the properties from th ...

Sending image from angular2 to asp.net core server

Currently, I have an asp.net core application with angular2 and I am facing an issue with uploading images. While I was able to upload images as byte[], I encountered a problem in checking if the uploaded file is actually an image on the backend. This led ...

Creating an enumeration within a class

I'm encountering difficulties when trying to declare an enum element within a class. Despite attempting various methods to declare the enum, I am unable to make it function properly. Here is the (non-functional) class: export class Device extends El ...

Angular 2 - Ensuring service executes only when boolean condition is met

I am currently dealing with a navigation menu that utilizes the ng2-page-scroll module. When scrolling through the page using hashtag links, I encountered an issue. If I navigate across routes, there is a delay in loading the data. As a result, the servic ...

Using ng-bootstrap with Bootstrap 4 beta as an npm dependency

After updating my npm dependencies in package.json to Bootstrap 4 beta and ng-bootstrap to 1.0.0-beta.5, I encountered an "UNMET PEER DEPENDENCY" for popper.js when running npm install due to its new addition as a dependency in Bootstrap 4 beta. Despite th ...

The functionality of the list feature seems to be malfunctioning, as it is appearing in a strange manner when displayed in console.log

When I tried to use a list to store data and display it later, I encountered the following issues: Using ListOfName.lenth resulted in [Photo of console][1]. However, using Console.log(ListOfName) displayed [Photo of List in console][2]. [1]: https://i.sst ...

Access the NativeScript DropDown widget by triggering it with another user interface element

As someone who is just starting out with Nativescript, I have a question that may seem basic to some. I wanted my dropdown to have a more web browser-like feel, so I decided to use the NativeScript DropDown widget by PeterStaev. I customized it with a Grid ...

Navigating through segment tabs on Ionic 3 with a simple swipe

In the code snippet provided, segments from Ionic 3 are used with ngSwitch and ngModel. However, I am looking for a way to switch between segment tabs by simply swiping on the content area, rather than tapping the tabs at the top. Is there a way to achieve ...

Is there a way for me to retrieve the value that has been set within the cy.get() function in Cypress using Typescript?

Is there a way to retrieve the value of the getLength function without it returning undefined? How can I access the value in this case? Here is my code snippet: const verifyValue = () => { const selector = 'nz-option-container nz-option-item&apo ...