Modify the array within a button located inside *ngFor loop

I am working with 3 buttons that loop through a list of links

links = [
    {
      name: "Link 1",
      id: "number1"
    },
    {
      name: 'Link 2',
      id: "number2"
    }
    {
      name: "Link 3",
      id: "number3"
    }
  ]

These buttons generate 3 buttons in HTML.

In addition, I have a DIV looping through items in "number1":

number1 = [
    {
      name: 'IT',
      address: 'Tokyo 4',
    },
    {
      name: 'Computer',
      address: 'Tokyo 4',
    },
    {
      name: 'Garden',
      address: 'Tokyo 4',
    },
    {
      name: 'Cars',
      address: 'Tokyo 4',
    }
  ]

The DIV renders H1 with {{ card.name }} and P with {{ card.address }}

Now, I need to switch from looping through "number1" to then looping through "number2" when the button number 2 is clicked. How can I achieve this?

(click)="change number1 to number2" - when I click button number 2 etc

Here's the PLUNKER link for reference: https://plnkr.co/edit/MfSx9MjoVtHprFtBHKDZ?p=preview

Answer №1

Here is an alternative method:

HTML code snippet:

 <li *ngFor="let link of links; let i = index">
      <button (click)="setNumber(i)">{{ link.name }}</button>
 </li>

Typescript code snippet:

...
number;
....
constructor(){
    this.number=this.number1
}

...
setNumber(index){
  console.log(index)
  switch(index){
    case 0:
      this.number = this.number1;
      break;
    case 1:
      this.number = this.number2;
      break;
    case 2:
      this.number = this.number3
  }
}

Check out the demo here

Answer №2

Indicate a different array variable and change the reference upon button click. Check out this Plunker for a demonstration.

//app component
import {Component, NgModule, OnInit, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <li *ngFor="let link of links">
      <button (click)="updateLinks(link.id)">{{ link.name }}</button>
    </li>

    <div *ngFor="let card of numbers">
      <h1>{{ card.name }}</h1>
      <p>{{ card.address }}</p>
    </div>
  `,
})
export class App implements OnInit {

  numbers: any[];

  ngOnInit(){
    this.numbers = this.number1;
  }

  updateLinks(linkId: string){
    this.numbers = this[linkId] as any[];
  }

  links = [
    {
      name: "Link 1",
      id: "number1"
    },
    {
      name: 'Link 2',
      id: "number2"
    }
    {
      name: "Link 3",
      id: "number3"
    }
  ]



  number1 = [
    {
      name: 'IT',
      address: 'IT Number 1',
    },
    {
      name: 'Computer',
      address: 'Computer Number 1',
    },
    {
      name: 'Garden',
      address: 'Garder Number 1',
    },
    {
      name: 'Cars',
      address: 'Cars Number 1',
    }
  ]



  number2 = [
    {
      name: 'IT',
      address: 'IT Number 2',
    },
    {
      name: 'Computer',
      address: 'Computer Number 2',
    },
    {
      name: 'Garden',
      address: 'Garder Number 2',
    },
    {
      name: 'Cars',
      address: 'Cars Number 2',
    }
  ]



  number3 = [
    {
      name: 'IT',
      address: 'IT Number 3',
    },
    {
      name: 'Computer',
      address: 'Computer Number 3',
    },
    {
      name: 'Garden',
      address: 'Garder Number 3',
    },
    {
      name: 'Cars',
      address: 'Cars Number 3',
    }
  ]


}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Answer №3

Is it possible to create multiple buttons and show/hide them conditionally based on a variable?

<button *ngIf="arrayNumber === 1" (click)="myFirstFunction()"></button>
<button *ngIf="arrayNumber === 2" (click)="mySecondFunction()"></button>

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

Tips for implementing owl carousel in Nuxt.REACT_UNITS_CODIFY

Is there a way to make the script function on every page without the need for these pages to be reloaded? I have the Owl Carousel script in my static folder, and I have already included it in nuxt.config.js as shown below: head: { title: 'title&ap ...

Utilize *ngFor to generate a class

In my angular project, I am working with a grid system and I am trying to create a class for each section of the grid to use in a CSS file. Below is the HTML code I am using: <mat-grid-list cols="5" rowHeight="20vh" [gutterSize]="'0px'"> ...

What is the Importance of Injecting Services, Constants, and Other Dependencies?

Imagine I go ahead and create an AngularJs service. Then I attach it to my module like this: angular.module('fooModule').service('myService', function(){ var service = { logSomething: function() { console.log(&a ...

Upgrade your React component by replacing componentWillReceiveProps with getDerivedStateFromProps

It's clear that componentWillReceiveProps has been deprecated and we are instructed to replace it with getDerivedStateFromProps. However, they don't seem to serve the same purpose at all. Moreover, getDerived... cannot access or setsetate. After ...

Splitting the identifier and the name into individual keys within a JSON object

I've got worker data stored in my database in JSON format, looking like this: {"45051-Cortador 1 Siloc": "hsgvs", "45063-Nihil impedit quia": "okbbd",} Each JSON Key contains an id and the name of the user. For ...

Retrieve specific data from MongoDB by querying for only one section of the information

In my latest project, I have successfully integrated a MongoDB database with a MEAN stack web application. Currently, the application is able to display the most recent set of data from the database. However, I am now faced with the challenge of refining t ...

Using Mongoose to delete multiple documents with the "like" operator

I am looking to remove all documents from a MongoDB collection that have a particular string in one of the fields. (I am working with mongoose) In SQL terms, the equivalent query would be: DELETE FROM users WHERE name LIKE '%test%' ...

What techniques does Twitter use to insert labels into text boxes?

When I visited the Twitter login page, I noticed something interesting - the labels for input fields were inside the input fields themselves. It seemed to be accomplished using a common trick involving javascript/jquery. Intrigued, I delved into the Twitte ...

Show avatar display name (default) in Canvas if image is unavailable

Is there a way to show an avatar by using the first letters of a name, similar to what Google does when the actual image is not available? https://i.sstatic.net/EMozW.png ========> https://i.sstatic.net/WfWN2.png I am looking for a solution that involv ...

establish an online repository with a data storage system

As a beginner in web development, my goal is to design a website with a database that can house all archive files. I want users to have the ability to delete existing files and upload new ones directly from the web page. Utilizing HTML, CSS, and JavaScrip ...

Unexpected blank space appearing above Grid component in Material UI

After implementing Grid for my post layout on the social media platform, I noticed an odd issue where extra white space appears above the GIF within the Grid element. How can I eliminate this unnecessary white space? Here are visual references: https://i. ...

Using Selenium Webdriver with Node.js to Crop Images

Currently, I am using selenium-webdriver in combination with nodejs to extract information from a specific webpage. The page contains a captcha element from which I need to retrieve the image. Unfortunately, all the code snippets and solutions I came acros ...

My coding skills leave much to be desired and I am encountering some challenges with my current Hangman Game project

I recently started learning JavaScript and I'm encountering some difficulties with my code. My assignment is to create a hangman game, and I've successfully implemented the loops for displaying "right" and "wrong" letters. However, I'm strug ...

What is preventing me from properly formatting my JSON object?

I am attempting to create a JSON object with inner objects. Here is the code I am working with, where $ids is an array containing some IDs: $result = array(); foreach ($ids as $value) { $tempArray = getCustomOptions($host, $dbUsername, $dbPassword, ...

Link the index of a nested array of numerical values to the corresponding index of an array containing strings

In my current project, I am trying to connect the array elements from foo3.flat() with the elements in foo2. For instance, if the 0th index in foo2 is 'address1' and the 0th index of foo3 is [1,2,3], all the individual numbers in [1,2,3] should b ...

After updating the TypeScriptOutDir configuration, breakpoints are not being reached

Currently, I am utilizing Visual Studio Professional 2013 Update 3 and have developed a Node console Application with the simple "hello world" log instruction. Setting a breakpoint in this instruction and running the debugger functions smoothly, hitting th ...

Simple code designed to determine the highest value is producing an IndexError due to the list index being out of range

Below is the code snippet I've been struggling with: num = int(input()) value = [] i = 0 maxval = 0 for x in range(num): value[i].append(input()) if value[i] > maxval: maxval = value[i] i = i + 1 print(value) I can't se ...

Using Express and Node.js to encode an image file as base64 data

I need to convert an image file into base64 format in order to store it as a string in a mongoDB database. This is my current approach: router.post('/file_upload',function(req,res){ function base64_encode(file) { var bitmap = fs.readFile ...

HTML/JS: Date and Time Tracker

Is there a way to use pure JS or bootstrap to create a component that can display a formatted date string based on provided instructions? For instance: <div class="my-datetime-formatter-and-display-er" value="Thu 30 Apr 20:12:08 EEST 2020" format ...

What is the method for sending a file using JavaScript?

var photo = 'http://cs323230.vk.me/u172317140/d_5828c26f.jpg'; var upload_url = 'http://cs9458.vk.com/upload.php?act=do_add&mid=62..'; var xmlhttp = getXmlHttp(); var params = 'photo=' + encodeURIComponent(photo); xmlhttp ...