Angular : How can a single item be transferred from an array list to another service using Angular services?

How to Transfer a Single List Item to the Cart?

I'm working on an Angular web application and I need help with transferring a single item from one service to another service and also displaying it in a different component. While I have successfully implemented transferring the entire array, I am facing challenges with moving just a single item. Any assistance would be greatly appreciated.


The goal is to transfer only the selected list item to the cart when the user clicks the Add to cart button, without transferring the entire list array.


buyGame.html file

<div class="col-xs-6">
    <a class="list-group-item clearfix" style="background-color:rgb(3, 0, 48)" *ngFor="let buying of buy">
        <div class="pull-left" style="max-width:330px">
            <h5 style="color:white">{{buying.names}}</h5>
            <p style="color:white">{{buying.desc}}</p>
            <button class="btn btn-danger ; pull-left" (click)= "onAddToCart()">Add To Cart</button>
        </div>
        <div>
            <span class="pull-right">
                <img [src]="buying.getImg" alt="image not loaded" class="img-responsive" style="max-height:100px">
            </span>
        </div>
   </a>
 </div>

buygame.service.ts file :

import { gameBuy } from "./buygame.model";
import { Injectable,EventEmitter } from "@angular/core";
import { cartService } from "./cart.service";

@Injectable()
export class gameService{

    private gameServ: gameBuy[] = [
        new gameBuy('batman','Batmobile and enhancements to signature features',"https://www.geek.com/wp-content/uploads/2016/02/batmans-625x352.jpg"),
        new gameBuy('GTA 5',
        "PlayStation 3 or Xbox 360 will be able to transfer their current Grand Theft Auto Online characters and progression to their choice of PlayStation 4 Xbox One or PC",
        "http://onlysp.com/wp-content/uploads/2015/01/maxresdefault.jpg")
    ];

    constructor(private cartSer: cartService){}

    getBuyingList(){
        return this.gameServ.slice();
    }

    addItemToCart(game:gameBuy){
        this.cartSer.addItem(game);
    }
}

buyGame.component.ts:

import { Component, OnInit,Input } from '@angular/core';
import { gameBuy } from '../shared/buygame.model';
import { gameService } from '../shared/buygame.service';

@Component({
  selector: 'app-buy-game',
  templateUrl: './buy-game.component.html',
  styleUrls: ['./buy-game.component.css'],
})
export class BuyGameComponent implements OnInit {

  @Input() buy:gameBuy[];

  constructor(private service: gameService) { }

  ngOnInit() {
    this.buy = this.service.getBuyingList();
  }

  onAddToCart(){
    this.service.addItemToCart(this.buy);
  }
}

cart.component.ts:

import { Component, OnInit} from '@angular/core';
import { cartModel } from '../shared/cart.model';
import { cartService } from '../shared/cart.service';
import { gameBuy } from '../shared/buygame.model';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css'],
})
export class CartComponent implements OnInit {

  cart:gameBuy[];

  constructor(private service: cartService) { }

  ngOnInit() {
    this.cart = this.service.getCartItem();
  }

}

cart.service.ts:

import { cartModel } from "./cart.model";
import { EventEmitter } from "@angular/core";
import { gameBuy } from "./buygame.model";

export class cartService{

    cartChanged = new EventEmitter<gameBuy[]>();
    private cart: gameBuy[] = [
        new gameBuy('Batman','Batman is a cool game','https://images-na.ssl-images-amazon.com/images/I/91lu5KHSm3L._SY445_.jpg'),
        new gameBuy('Gta 5','online game of GTA','https://www.rockstargames.com/V/img/global/order/mobile-cover.jpg')
    ];

    getCartItem(){
        return this.cart.slice();
    }

    addItem(cart:gameBuy){
        this.cart.push(cart);
        this.cartChanged.emit(this.cart.slice());
    }
}

cart.model.ts:

export class cartModel{
    constructor(public cartName: string,public cartDesc: string,public cartImage:string){}
}

buygame.model.ts:

export class gameBuy{
    constructor(public names:string, public desc:string, public getImg:string){}
}

Answer №1

Make sure to specify the exact item you want added to the cart in your template:

(click)= "onAddToCart(buying)"

Next, pass it directly to your service as a parameter in the onAddToCart method:

onAddToCart(buying: gameBuy){
  this.service.addItemToCart(buying);
}

Additionally, ensure that your buygame service method accepts a single item instead of a list:

addItemToCart(game: gameBuy){
    this.cartSer.addItem(game);
}

Lastly, update your cart service to push a single item:

 addItem(cart:gameBuy){
    this.cart.push(cart);
    this.cartChanged.emit([...this.cart]); // consider using slice() for a copy if needed
}

Answer №2

Consider including the index parameter in your click event handler like this: (click)="onAddToCart(index)", and retrieve it from your array.

Alternatively, you can pass a single object to the onAddToCart method like this: (click)="onAddToCart(buying)"

Then make sure to handle it properly in your TypeScript code.

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 assigning a numerical value to an array and showcasing it in a listview

I have a dilemma involving two activities. The first activity displays a list of items using a ListView. In the second activity, I also want to display a list of items, but the content will vary based on the position of the element selected in the first ac ...

JSF CommandLink malfunctions on Firefox when reRendering an entire form

I am currently working on a JSF 1.2 application (Sun RI, Facelets, Richfaces) that was previously designed only for IE6 browsers. However, we now need to extend our support to include Firefox as well. On one of the pages, there is a form with a button tha ...

Audio suddenly no longer working after transferring project to React

View my reproducible example here. This is a demonstration of the issue I am facing. Previously, when the page consisted only of static html with javascript, the sounds were functioning correctly. However, after refactoring into a React app, the sounds ha ...

Code snippet for a click event in JavaScript or jQuery

I initially wrote the code in JavaScript, but if someone has a better solution in jQuery, I'm open to it. Here's the scenario: I have multiple questions with corresponding answers. I want to be able to click on a question and have its answer dis ...

Tips for accessing CSS properties on the img tag

I could use some assistance with CSS. I am in the process of creating a tree structure using many <ul> and <li> tags. The issue arises when I have multiple <li> elements with a specific class, each containing an <img> tag. How can ...

issue with jQuery not properly selecting options based on text

I have three select elements in my code, each containing 3 or 4 options. An "Apply All" button is placed on the first file row. When a user selects a sheet name on the first file and clicks the Apply All button, it should automatically select the same she ...

Adjust THREE.PerspectiveCamera's distance without altering its viewing orientation

I have a PerspectiveCamera in THREE.js positioned somewhere in space as a child of a mesh. The camera is currently looking at the mesh with local coordinates [0, 0, 0]. I am looking for a way to change the distance of the camera from the mesh without chang ...

Tips on displaying data in pie chart legend using react-chartjs-2

I am currently using a pie chart from react-Chartjs-2 for my dashboard. The requirement is to display both the label and data in the legend. I have implemented the following component in my application: import React, { Component } from "react"; ...

What is the best method for obtaining a modified image (img) source (src) on the server side?

Having some trouble with a concept in ASP.Net that's causing me quite the headache. I am fairly new to ASP.Net and struggling with something that seems much easier in PHP. I created an img element with an empty src attribute : <img runat="server" ...

preserving the status of checkboxes based on an array of binary values

I am trying to figure out how to restore the state of checkboxes in an ORACLE APEX tabular form. The selection is made in the first column using the APEX row selector f01. After saving the checkbox state in a collection and then transferring it to an arra ...

Utilizing various layouts in ASP.NET MVC with AngularJS

I am setting up two different layouts, one for visitors and one for management. Routes: app.config(['$routeProvider', function ( $routeProvider) { $routeProvider .when('/', { templateUrl: 'Home ...

Can anyone explain the meaning of (0, _jquery["default"]) in relation to jQuery selectors or functions?

Trying to implement jQuery on an offline page can be challenging when dealing with EmberJS, RequireJS, and other technologies. My goal is to replace complex code with simple jQuery. The HTML below should respond to user interaction: Loading i ...

JavaScript format nested data structure

For my latest project, I am working on a blog using Strapi combined with Nuxt. To fetch the categories and articles data for my blog, I send a JSON object from my front-end application using Axios. { "data": [ { "id": 1, ...

This error message indicates that the function window.parent.sayhello is not available or defined

I have a JavaScript function that is defined in a JScript.js file, which is located on the masterpage. My goal is to call the sayhello function from this file on the inIframe.aspx page. The inIframe.aspx page is nested within the webform1.aspx page, and th ...

The error you are seeing is a result of your application code and not generated by Cypress

I attempted to test the following simple code snippet: type Website = string; it('loads examples', () => { const website: Website = 'https://www.ebay.com/'; cy.visit(website); cy.get('input[type="text"]').type(& ...

Effortlessly collapsing cards using Angular 2 and Bootstrap

Recently delving into Angular 2 and Bootstrap 4, I set up an about page using the card class from Bootstrap. Clicking on a card causes it to expand, and clicking again collapses it. Now, I want to enhance this by ensuring that only one card is open at a ti ...

The jQuery .each function is malfunctioning specifically on Google Chrome browsers

I developed a web application that utilizes jQuery to automatically submit all forms on the page. The code snippet is as follows: $('form').each(function() { $(this).submit(); }); While this functionality works perfectly in Internet Explore ...

I am puzzled by this error in Typescript: "Why does the element have an 'any' type when the Object type lacks an index signature?"

Looking to extract an array of keys from an object with nested properties, my current code: public static getKeys(obj: Object) { let keys: string[] = []; for (let k in obj) { if (typeof obj[k] == "Object" && obj[k] !== null) { ...

Guide to implementing optional localization strings in React-Router paths

Incorporating react-router, I aim to implement internationalization for links following this format: domain.com/langISO/countryISO2/page Here are some examples of valid routes: domain.com/ -> Home Page domain.com/en/us -> Home Page domain.com/fr/f ...

What are some methods to conceal an email address using Javascript?

let user = 'alex'; let domain = 'gmail.com'; let send = 'msg'; document.getElementById("email").href = "ma" + send + "ilto:" + user + "@" + domain; <a id="email"> <img src="imgs/pic.jpg"> </a> I have been w ...