Angular 4: Retrieving the selected element's object from a collection of elements

In my x.component.html file, I have a list of objects that are being displayed in Bootstrap cards like this:

<div *ngFor="let item of items | async">
    <div class="row">
         <div class="col-lg-6">
              <div class="card card-accent-primary">
                   <div class="card-header">
                                            {{item.name}}
                        <label class="switch switch-text switch-pill switch-primary float-right mb-0">
                             <input class="switch-input" type="checkbox" (change)="onSwitchItem($event)">
                             <span class="switch-label"></span>
                             <span class="switch-handle"></span>
                       </label>
                    </div>
                    <div class="card-body"></div>
              </div>
         </div>
    </div>
</div>

I'm trying to figure out how to access the selected items in my x.component.ts file. Is there a way to directly get the item object without using indexes?

As of now, I am assigning an index to each item using angular property binding [id]="item.index", and then accessing the items array based on the index.

Answer №1

To implement this functionality, you can follow these steps. Begin by iterating over an array that keeps track of the added child components. When a check button is clicked, it triggers the addition of a new element to the array. Then, using ngFor, iterate over the array again to add the new child component to the DOM.

Parent Component:

HTML

<div *ngFor="let item of items | async">
   <child-card [item]=item></child-card>
</div>   

TypeScript:

 childs = [];

  add() {
    this.childs.splice(0,0,this.childs.length+1);
  }
}

Child Component:

HTML

<div class="row">
         <div class="col-lg-6">
              <div class="card card-accent-primary">
                   <div class="card-header">
                                            {{item.name}}
                        <label class="switch switch-text switch-pill switch-primary float-right mb-0">
                             <input class="switch-input" type="checkbox" (change)="onSwitchItem($event)">
                             <span class="switch-label"></span>
                             <span class="switch-handle"></span>
                       </label>
                    </div>
                    <div class="card-body"></div>
              </div>
         </div>
    </div>

TypeScript

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

@Component({
    selector: 'card-child',
    ....
}
....
export class cardChildComponent {
    @Input() item;
....
   }

Plunker

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 including images while drafting an article

In my current project, users are able to write articles. One feature of the editor is the ability to upload photos and include them in the article. While this functionality works well, there is an issue with how the photos are handled and stored. Each ar ...

A Guide on Adding Excel-Like Filtering Functionality to AngularJS

I am struggling to implement a simple Excel-like filter for a table using AngularJS (v.1). I have shared my code snippet below and would appreciate any help to show filtered data in the table after checking a checkbox and clicking on the OK button. I have ...

Tips for effectively handling sessions with a complex database system

Having a single user portal account, I access it with two distinct usernames in separate tabs. Performing a hard refresh (ctl+f5) simultaneously in both tabs results in the same user account opening in both tabs, regardless of which username I use. How ca ...

Django RGBField cannot locate jQuery

Working on a project that utilizes an RGBField, the following script is injected into the template (nested deep within django's structure, as its exact location remains elusive): <script type="text/javascript"> (function($){ ...

An error occurred stating 'TypeError: jsdom.jsdom is not a function' while using the paper-node.js in the npm paper module

Recently, I added the webppl-agents library to my project, including webppl and webppl-dp. However, when attempting to execute the command line test, I encountered some difficulties. It seems that there is a dependency problem with jsdom from the npm paper ...

Data that is loaded asynchronously will not display rendered

I have async data loading via jayson from a server. After the data has finished loading, the boolean "loading" is set to false but my content does not re-render. Even though I can see on the console that the data was loaded correctly. var App = new Vue( ...

Modify the row's background color after clicking the delete button with jquery

Greetings, I am facing an issue with changing the color of a row in a table when clicking on a delete button. Despite trying various methods, I have not been successful. How can I modify the ConfirmBox() method to change the row's color? Your assistan ...

Tips for troubleshooting and resolving the npm ERR! code E404 issue in Vue.js when implementing a datepicker

I am a newcomer to Vue.js and I am currently exploring the use of a datepicker from However, upon importing the script for usage, I encountered the following message: 'VMdDateRangePicker' is declared but its value is never read.ts(6133) Cou ...

Issues with the navigator.contacts.find function occurring when using cordova or phonegap

I am attempting to retrieve the contacts stored on a mobile device. The code snippet I am using is not functioning as expected - specifically, the navigator.contacts.find method isn't producing any outcomes. There are no error messages or success conf ...

React JS Issue: Real-time Clock not updating in React component

I have a react application designed for attendance tracking. The issue at hand is that the time displayed does not update in real-time. Once the app is initially rendered, the time remains static. (It only updates when the app is reloaded) The code snipp ...

A React component that exclusively renders component tags

After successfully loading index.html with no JavaScript errors, I ran into an issue where nothing was rendering on the page. Upon inspecting the webpage, all I could see was a tag and nothing else. It turns out that I have a component called "list". The ...

Converting Hexadecimal Values to Base32-Encoding Using Javascript

I'm encountering a problem with converting a function from Ruby to Javascript (specifically node.js, but I prefer a solution that is compatible with browsers, if possible). Here is the hex-formatted sha256 digest: "0b08dfe80a49490ae0722b9306ff53c5ab ...

Chrome and Firefox provide excellent compatibility for running JavaScript, whereas Safari may encounter some issues. Opera's performance with JavaScript can be quirky

Disclaimer: I'm new to web design and development. I have encountered an issue with posting information from a form built on CodeIgniter using jQuery. The form posts successfully in Chrome and Firefox, with the current page automatically reloading. H ...

Tips for implementing a JavaScript Material Design framework in ReScript code?

I am attempting to integrate the material-ui library into a Rescript/React application. The code snippet below demonstrates how to display a button: @module("@material-ui/core/Button") external button: string = "default" @react.compone ...

ASP.NET service with an added quotation mark in the JSON response!

I am trying to make a web service method call in JavaScript within an ASP.NET 3.5 environment. After inspecting the result using Firebug, I found the following: {"d":"[{\"TI\":\"www\"},{\"TI\":\"www1\"}]"} It seem ...

Error message: The context object is not iterable. Please note that it must be iterable in order to avoid

While going through a React course on Context API, I encountered an error that says "context is not iterable TypeError: context is not iterable". Has there been any new syntax introduced? If so, please let me know. Here is the content of app.js: I'v ...

The word "yargs" will not activate a command within a script

I have a NodeJs script that requires parsing command line arguments. Here is the code I have written: import yargs from "yargs"; import { hideBin } from 'yargs/helpers'; //.... yargs(hideBin(process.argv)).command('--add-item ...

Setting up a chat feature in a Laravel application: A step-by-step guide

Looking to Enhance My Web-Application I have been working on a web-application that utilizes: Laravel for the back-end Angular for the front-end. Milestone Achieved! I successfully implemented the entire user authentication process including: User Aut ...

My code in NodeJS is not executing in the expected order due to its asynchronous nature

handleRegistration: function (user, req, res, next) { console.log('handleRegistration activated'); user.getData(function(err, info) { if (err) { console.log(err.toString, "error message"); return next(err); } e ...

Combining Socket.io with AJAX for real-time web applications

I am currently working on a web application that relies on Socket.io for delivering notifications to users. I'm wondering if it would be more beneficial to utilize Socket.io exclusively for all client-server communication, or if mixing in traditional ...