Encountering problems with displaying the index value in *ngFor directive in Angular 5

I am encountering a problem with rendering the index of *ngFor directive for a specific scenario as described below.

Suppose we have an array of objects like this:

this.temp = [
  {name:'John',age:24,visibility:'visible'},
  {name:'Kane',age:26,visibility:'hidden'},
  {name:'Ross',age:28,visibility:'visible'},
  {name:'Lui',age:21,visibility:'visible'}
]

To display this in my app.component.html file, I have the following HTML:

<div *ngFor="let user of temp; let i = index">
 <div *ngIf="user.visibility === 'visible' ">
    <div>{{i+1}}</div>
    <div>{{user.name}}</div>
 </div>
</div>

So, based on the array example above, it renders users as:

1. John
2. Ross
3. Lui

Now, there is a button called 'Change visibility' next to each user in my UI, where clicking on it toggles the visibility state of the user from 'hidden' to 'visible' and vice versa.

However, when clicking the button next to John, even though its visibility is set to hidden, the rendered UI shows:

2. Ross
3. Lui

My desired output is:

1. Ross
2. Lui

How can I ensure that the index renders correctly?

The constraint here is that I cannot modify or change the length of my this.temp array. Essentially, I require the entire array with only the visibility property updated based on user actions.

Any assistance would be appreciated.

Answer №1

To optimize your code, start by filtering the array:

<div *ngFor="let user of temp.filter(us => us.visibility === 'visible'); let i = index">
 <div>
    <div>{{i+1}}</div>
    <div>{{user.name}}</div>
 </div>
</div>

By filtering the array first, you avoid analyzing all items and achieve a more efficient and desired output.

Cheers!

Answer №2

If you want to get the desired output, you can utilize the Pipe feature as shown below:

HTML snippet

<div *ngFor="let user of temp | visiblefilter ; let i=index">
    <span>{{i+1}} {{user.name}}</span> <button name={{user.name}} (click)="onHide($event)">Hide</button>
</div>

PIPE implementation

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'visiblefilter',
    pure: false
})
export class VisibleFilterPipe implements PipeTransform {
    transform(items: any[]): any {
        return items.filter(({visibility}) =>visibility=='visible');
    }
}

For a live demonstration, feel free to check out this stackblitz link

Answer №3

Implement a custom trackby function for the ngFor directive:

*ngFor="let user of temp; let i = index; trackBy: customTB"

customTB(index, item) {
  return index + ' - ' + item.name;
}

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

Error: React 404 - Unable to make a POST request with

I am new to utilizing Axios and Node.js as a backend technology. I recently inherited some React code for a login page and I'm struggling to understand why I'm unable to send a POST request to the backend. Below is my .env file: REACT_APP_BACKEN ...

What are the steps for implementing the Ionic 2 Pulling Refresher feature in my application?

Hey everyone, I'm currently working on developing a mobile app using AngularJS 2/Ionic2. I am facing an issue with implementing a pull-to-refresh feature in my app. We followed the steps outlined in this link, and while we were able to get the page to ...

Angular 2 Guide on macOS Sierra Shows "Page Not Found" Error in Web Browser

I've been delving into Angular 2 with TypeScript on my OS X machine. Following the tutorial to the T, I didn't encounter any errors during compilation. Upon executing the npm start command, everything seemed to be smooth sailing as a new tab open ...

A guide on coding the source tag script for a payment form in CodeIgniter, specifically for a JavaScript form

Scenario: I have a variable called $data['tabdata'] that I am passing from controller C to view V. This variable includes a script element pointing to http://example.com/1.js. Problem: The script in 1.js is not running properly in the view. This ...

Arrange array items according to the values of two attributes

Within my array of N objects, each object is structured with the following properties: { id: 'an id', description: 'a description', isUser: true/false } My goal is to sort this array based on two criteria: Firstly, any object w ...

Revamping JSON structure by identifying id references

I recently attempted to update the city name within the JSON object provided below. "City":[ { "Name":"Delhi", "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd", "Towns":[ ...

Creating an interactive webpage with Javascript and HTML

I'm facing a challenge with my component setup, which is structured as follows: import { Component, VERSION } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ ...

Is it possible to utilize a single node_modules folder for multiple Angular 2/4 projects?

As I dive into the world of Angular, I've noticed that creating a new project can be time-consuming due to the 100MB "node_modules" folder that the CLI generates. The contents of this folder are repetitively consistent across projects, with few change ...

Using Node.js to efficiently parse JSON data into customizable PUG templates

I have a challenge where I am parsing JSON data into elements called homeCards. To achieve this, I use Axios to request the JSON data and then utilize a for loop to cycle through it. Inside my Axios function, I extract the fields I need and store them in v ...

Experience the power of module federation in Next JS without using the @module-federation/nextjs-mf package

Currently transitioning from Java to JavaScript, I am working on a Next.js project. I have a requirement to share the client component from this Next.js project with another project built on React. Upon discovering module federation, I successfully created ...

Incorporating JSON data into an HTML table

Looking to populate an HTML table with JSON data, but struggling with parsing and appending the data correctly. Can anyone provide guidance or assistance? <!DOCTYPE html> <html> <head> <title>JSON Demo</title> < ...

jQuery Ajax allows scripts to be contained within a page, even if the page itself is empty

Utilizing jQuery ajax to display an HTML page that includes javascript functions, here is my code: function ChartBook() { $.ajax({ url: '/Charts/ChartBook', dataType: 'html', id: 1, ...

cycle through options of radio buttons

How can I display items of radio buttons, with the values of these items coming from a backend api? <div class="input-group col-md-9 input-group-sm"> <label>gender</label> </div> <!-- TO CORRECT ...

Error encountered during production build of Angular 6 Universal with server-side rendering (SSR

I have recently delved into Angular 6 and managed to nearly complete my app. However, I am encountering some struggles with server-side rendering (SSR). Following a tutorial on SSR at this link, I tried running the command npm run build:ssr && npm ...

Utilize Google Sheets to extract information from a web address containing quotation marks

I am currently utilizing a script called "ImportJSON" developed by paulgambill https://gist.github.com/paulgambill/cacd19da95a1421d3164 The URL I am working with contains quotes characters For instance: http://SomeAPIULR?{"Type": "SomeType"}&APIKE ...

Utilizing ES6 JavaScript for Creating Static Methods and Angular 2 Services

During the development of an Angular 2 app involving multiple calculation services, I encountered some interesting questions: Is it beneficial to use static in an Angular service provided on the application level? Or is it unnecessary? How does a static ...

Steps to filter types by a singular property assessment

export type HalfSpin = { halfspin: string } export type FullSpin = { fullspin: string } export type SpinType = | HalfSpin | FullSpin export function isHalfSpin(_: SpinType) ...

What is the process for generating an API endpoint in Next.js that includes a query string?

I am currently working on setting up an API endpoint in Next.js, specifically the following one: /api/products/[name]?keyword=${anykeyword}. To accomplish this, I understand that I have to create it within the pages/api/products/[name] directory in index ...

Ways to adjust timestamps (DayJs) by increments of 1 minute, 5 minutes, 15 minutes, 30 minutes, and more

Currently, I am exploring time functionality within React Native by utilizing DayJs. I have noticed a slight inconsistency when comparing 2 different points in time to calculate the time difference. Typically, everything works smoothly such as with 10:00 ...

Angular 2 is throwing an error stating that the argument 'ElementRef' cannot be assigned to the parameter 'ViewContainerRef'

I'm developing an Angular 2 application with angular-cli, but when I include the following constructor, I encounter the following error: Error Argument of type 'ElementRef' is not assignable to parameter of type 'ViewContainerRef&apos ...