Switch the visibility of all local variables in *ngFor from an external loop

Imagine having an *ngFor loop where a local variable is defined like this:

<div *ngFor="let item of items">
  <p>{{item.name}}</p>
  <div *ngIf="item.colorVisible">{{item.color}}</div>
  <button (click)="item.colorVisible = !item.colorVisible">Toggle Color</button>
</div>

You are iterating through an array of objects, with a sample array in TypeScript being:

export class AppComponent {
  items = [
    {
      name: 'John',
      color: 'Green'
    },
    {
      name: 'Jim',
      color: 'Blue'
    },
    {
      name: 'Jane',
      color: 'Orange'
    }
  ]
}

Is there a way to have a button outside the loop that toggles all variables and updates the scope?

Take a look at this StackBlitz demo.

Answer №1

To easily toggle the visibility of colors in your component, you can add a boolean property and create a method to iterate through your items.

Updated Component:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public allVisible = false;
  items = [
    {
      name: 'John',
      color: 'Green',
      colorVisible: false
    },
    {
      name: 'Jim',
      color: 'Blue',
      colorVisible: false
    },
    {
      name: 'Jane',
      color: 'Orange',
      colorVisible: false
    }
  ]

  toggleAll() {
    this.allVisible = !this.allVisible;
    this.items.forEach((item) => {
        item.colorVisible = this.allVisible;
    });
  }
}

Updated Template:

<button (click)="toggleAll()">Toggle All Colors</button>

You can view the changes made in this updated StackBlitz version.

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

I'm feeling very confused by how PHP handles foreach loops with arrays and objects

I am currently encountering a roadblock while working with the leafly API. I am extracting data from their API for dispensary reviews using the following code: $data = wp_remote_get(http://data.leafly.com/locations/denver-relief/reviews?skip=0&take=1 ...

Determining the accurate object from a nested type in Typescript is essential

I'm currently facing a challenge with Typescript in inferring the correct object within a switch case. I find it puzzling why my scenario works as expected with a union type but not with an object. Here is the code from the playground link: interface ...

The ngx-datatable is returning an error message stating that it cannot read the property 'indexes' of an undefined

In my project, I am using ngx-datatable version 15.0.2 and Angular version 8.1.0. Recently, I encountered the following error: ngx-logger.js:852 2019-07-30T15:04:42.930Z ERROR [main.js:4696] TypeError: Cannot read property 'indexes' of unde ...

Arrange the array so that the item is placed at the beginning while maintaining the original order

Currently facing a roadblock with this particular issue. I am attempting to create a function that accepts an index as input and rearranges the element at that index in an array to be placed at the beginning, while keeping the order of the other elements a ...

Trouble detecting change event in Angular 2 form with <ng-datepicker> component

Hello, I am currently working with the code provided below and I need the date selection to trigger a specific function. However, I am unsure which function to use in this case. I have tested several options such as (dateSelect), (onDateChange), (selecte ...

What's the best way to group rows in an angular mat-table?

I am working on a detailed mat-table with expanded rows and trying to group the rows based on Execution Date. While looking at this Stackblitz example where the data is grouped alphabetically, I am struggling to understand where to place the group header c ...

What is the best way to ensure that the function is referencing the class appropriately?

Typically when using this, it points to the class being referenced. However, in this scenario, this is set to dataChannel. How can I make this point back to VideoService? Thank you. export class VideoService { dataChannel:any; setupPeerConnectio ...

Efficiently and Effectively Comparing Two Arrays of Objects in JavaScript

Let's imagine we have 2 sets of data arrays, A (original) and B (updated). var A = [ { id: 1, value: 'Product Name 1' }, { id: 2, value: 'Product Name 2' }, { id: 3, value: 'Product Name 3' }, { ...

What is the best way to tally identical values within a Multidimensional Array using Javascript?

How do I find the number of similar values in this 2D array? Need some help! var data = [[0,0],[1,0],[1,0],[1,0],[1,0],...,[7,0]] I am looking for something like this: var data3d = [[0,0,1],[1,0,12],[2,0,25]...... I want to store the count value in the t ...

How can I convert the numbers printed into an Array in Java?

I've crafted a solution to eliminate duplicates from an array provided by the user. However, rather than displaying the unique numbers in an array format, they are instead printed as individual numbers. Is it possible to convert these numbers into an ...

What is the process for transferring data processed in Python to Node.js and then forwarding it to Angular?

I am a newcomer to Angular and I'm looking for a way to showcase JSON data from Python in my Angular app using Node.js. I have already utilized child processes to establish the connection between Python and Node.js, but I am facing a challenge on how ...

What is the best way to set up a reactive form in Angular using the ngOnInit lifecycle

I have been facing an issue while trying to set up my reactive form with an observable that I subscribed to. Within the form class template, I used the ngOnInit lifecycle hook to fetch the desired object, which is the product. The first code snippet repre ...

Avoiding repeated form submissions within a system that does not retain session state

While previously working in PHP, I used to generate a unique id in order to prevent duplicate form submissions. This involved storing the id in a session variable and comparing values on submission. Although I never found this solution ideal, I struggled t ...

Python2 - Error: IndexError encountered while attempting to create a nested array

Here is a snippet from my script: k = int(raw_input()) order = [] o = [] for i in range(1, k): o.append(raw_input()) order.append([int(n) for n in list(o[i])]) Subsequent to these input lines, I've been encountering the following error: 3 2 ...

Tips for updating input text rendered by an array map in REACTJS

const information = [ { topic: "Greeting the Universe", businesses: [ "Google", "Apple", "Facebook" ] } ]; class UserInterface extends React.Component { render() { return (      <ul>       {informatio ...

Include a sub-array in each element of the main array

In my coding project, I am working with a parent array referred to as $list. When I use the var_dump($list); function, it outputs the following structure: array (size=10) 0 => array (size=4) 'id' => string '6' (lengt ...

What is the proper way to code this complex function using Typescript?

This is an interesting function: function extractKey(obj, key) { var result = {}; Object.keys(obj).forEach(k => { result[k] = () => k; }); return key(result)(); } Here is a variation of the code: getKey<T>(obj: T, keyGetter: (o ...

Key numbering for PHP array elements

Here is the code I am working with: $str = array(fgets($da, 1024)); print_r($str); I am attempting to create an array in PHP from a dynamic output. However, I have noticed that all the objects have keys [0]. I would like to assign a different key n ...

Is there a way to streamline this function call that appears to be redundantly repeating the same actions?

I have developed a function to search for blog posts, prioritizing titles over excerpts and excerpts over content when added to the containsQuery array. While the code seems to be working well, I have noticed that there is a lot of redundant code. How can ...

The compiler is reminding me that a function is required to return a value, even though I am already returning one

Recently, I decided to learn C++ and started working on a Stack Class implementation using arrays. However, encountered an error while trying to compile my program: Stack::pop : function must return a value. Here is the code for my pop function: int pop ...