What is the best method to transfer data between two div elements?

I'm currently working on a shopping app and trying to implement a feature where clicking on a product adds it to the checkoutList. However, I'm facing an issue where when a product is clicked, no data is being sent and I am getting 'undefined' back. I have created a service called messenger.service.ts which includes the following function triggered by the button:

export class MessengerService {
  subject = new Subject()

  constructor() {}

  sendMsg(product) {
    console.log(product)
    this.subject.next(product) // triggering an event
  }

  getMsg() {
    return this.subject.asObservable()
  }
}

Here is the component that displays the products that can be added to the checkoutList:

export class ProductListComponent implements OnInit {
  productList: Product[] = [];

  @Input() productItem: Product;

  constructor(private productService: ProductService, private msg: MessengerService) {}

  ngOnInit(): void {
    this.productList = this.productService.getProducts();
  }

  onAddToCheckoutList() {
    this.msg.sendMsg(this.productItem);
  }
}

The component that listens to the service:

<div class="col-3" *ngFor="let product of productList">
  <a href="#" class="list-group-item clearfix" [productItem]="product" (click)="onAddToCheckoutList()">
    <span class="pull-left">
                        <img 
                        style ="height: 72px;"
                        [src]="product.imagePath"
                        alt="{{ product.name }}" >
                    </span>
    <div class="productName">
      <p> <b> {{product.name}}  </b> <br> Price: €{{product.price}}</p>
    </div>

  </a>
</div>

To provide a visual representation of the application, here is a screenshot:

Answer №1

The function for handling clicks should include the item as a parameter:

(click)="addToCart(item)"

In your component's code, update the method to utilize this new parameter like so:

addToCart(item){
  this.cart.addItem(item)
}

If there are no additional features not mentioned in the query, you may also consider removing @Input() cartItem: Cart.

Answer №2

Make a modification to the 2-way binding [(...)]:

<div class="col-3"  *ngFor="let product of productList">
                <a href="#" 
                class="list-group-item clearfix" 
                [(productItem)]="product"
                (click)="onAddToCheckoutList()"
                >
                    <span class="pull-left">
                        <img 
                        style ="height: 72px;"
                        [src]="product.imagePath"
                        alt="{{ product.name }}" >
                    </span>
                    <div class="productName">
                        <p> <b> {{product.name}}  </b> <br>  Price: €{{product.price}}</p>
                    </div>  
                    
                </a>  
            </div>

However, this way will cause the productItem to always be the last item in the productList and not selected by clicking.

To resolve this issue, adjust your logic code as follows. Now, when you select an item, it will be passed into onAddToCheckoutList() and the function to add the item to the itemList in MessengerService will be called:

In your html file:

<div class="col-3"  *ngFor="let product of productList">
                <a href="#" 
                class="list-group-item clearfix" 
                (click)="onAddToCheckoutList(product)"
                >
                    <span class="pull-left">
                        <img 
                        style ="height: 72px;"
                        [src]="product.imagePath"
                        alt="{{ product.name }}" >
                    </span>
                    <div class="productName">
                        <p> <b> {{product.name}}  </b> <br>  Price: €{{product.price}}</p>
                    </div>

                </a>  
            </div>

In your .ts file:

export class ProductListComponent implements OnInit {


productList: Product[] = [];

@Input() productItem: Product

  constructor(private productService: ProductService, private msg: MessengerService) { }

  ngOnInit(): void {
    this.productList = this.productService.getProducts()
  } 

  onAddToCheckoutList(productItem){
    this.msg.sendMsg(productItem)
  }
}

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

Select characteristics with designated attribute types

Is there a way to create a type that selects only properties from an object whose values match a specific type? For example: type PickOfValue<T, V extends T[keyof T]> = { [P in keyof (key-picking magic?)]: T[P]; }; I am looking for a solution w ...

The default sanitizer of Express-validator fails to function properly when it is linked with other sanitizers

I am encountering an issue with the default() sanitizer from express-validator. It seems that when I include it in a chain, like this: body("children").optional().isArray().default([]), the default function does not have any effect, leading to ch ...

Fetching Data Using Asynchronous API Calls

My goal is to retrieve all results consistently from the API, but I am encountering varying outcomes. The for loop seems to be skipping some requests and returning a random number of records. Can anyone provide assistance? I have experimented with using t ...

Exploring Angular 2: How to Retrieve the Value of a Radio Button

How can I retrieve the value of the radio button that is clicked in app.component.html from within app.component.ts? app.component.html <div class="container"> <div class="row"> <div class="col-sm-3 well" style="width: 20%"> ...

Multiple subscriptions without having to recalculate the shared components

const ex = ajax.getJSON('https://httpbin.org/get?a=24'); ex.pipe(pluck('args')).subscribe(x => console.log('Arguments: ', x)); ex.pipe(pluck('headers')).subscribe(x => console.log('Response Headers: ' ...

What is the proper method for implementing an event listener exclusively for a left mouse click?

Is there a way to make Phaser recognize only left mouse clicks as click events, excluding right and middle clicks? Check out this Phaser example at the following link: https://phaser.io/examples/v2/basics/02-click-on-an-image. ...

The role-based login feature in Angular/Ionic is expecting 1 argument, however it received 2 arguments resulting in error code ts(2554

Encountering the error message "Expected 1 arguments, but got 2.ts(2554)" on this line involving the user object: Storage.set(TOKEN_KEY, user); Here is the complete code snippet of the method in question: login(credentials: any): Observable<any>{ ...

The problem with Angular Jasmine Karma is with the [SortKey] and various elements present on the page

While working on building some pages and integrating jasmine .spec files for karma to run with Angular 5, I encountered numerous errors. For example, when using Chrome and checking the command prompt, I came across: Error: Template parse errors: Can& ...

I am looking for guidance on removing the bottom line from the ionic 4 segment indicator. Any advice or tips on

.segment-button-indicator { -ms-flex-item-align: end; align-self: flex-end; width: 100%; height: 2px; background-color: var(--indicator-color); opacity: 1; } I am a beginner in hybrid app development and ...

Troubleshooting a CSS problem within mat-autocomplete component in Angular 7

While using mat-autocomplete, I noticed that when I select an option from the dropdown and then scroll through the main bar, the dropdown menu does not move along with the autocomplete input field. view image here Here is the code snippet: <td width ...

Configuring IIS routing for seamless integration with Angular routing

After deploying my front-end Angular application on an IIS server and my back-end ASP.NET web API application on a separate server, I encountered an issue. Even though I can access the web page when visiting the Angular application's URL and navigate ...

Perform a unit test on a variable declaration within the ngOnInit() function

As I dive into the world of TDD and revisit all the Angular tutorials available to me, I am determined this time to achieve 100% code coverage in my unit tests. Despite my efforts, I have stumbled upon a question that seems too simple to find an answer to ...

In ngx-datatable, I’ve set up a unique custom dropdown component within every header cell

I have a custom dropdown component in each header cell of my ngx-datatable. However, when I click on the dropdown, it is going inside the body of ngx-datatable. Can someone please help me resolve this issue? My development environment includes Angular 4.0 ...

Why isn't the parent (click) event triggered by the child element in Angular 4?

One of my challenges involves implementing a dropdown function that should be activated with a click on this specific div <div (click)="toggleDropdown($event)" data-id="userDropdown"> Username <i class="mdi mdi-chevron-down"></i> </d ...

What are the ways in which Angular can offer assistance to Internet Explorer 9?

The news is out - the Angular team has just announced their support for Internet Explorer 9! This revelation has left me wondering, how is it even possible? Currently, I am an avid user of AngularJS and have dedicated time to studying its ins and outs. Fr ...

Is there a way for me to confirm the presence of a particular object within an array and return a true value

I am working on a form in Angular that includes checkboxes. I want to automatically check the checkbox if the user has a specific role. Here is my current approach: <form [formGroup]="rolesForm"> <label formArrayName="roles" *ngFor=" ...

Setting up Linter and Prettier to enforce rules in HTML

My team and I in our Angular project have established certain rules regarding template formatting and Sass stylesheets. We utilize linter and prettier within our project. I am now curious if there is a way to configure these tools to automatically enforce ...

Unable to display JSON object in HTML in Angular due to a pipe error

Whenever I include the following code snippet: {{form}} The output is: [object Object] But when I modify it to: {{form | json}} An error occurs: TypeError: Converting circular structure to JSON --> starting at object with constructor 'TView&a ...

Looking to dynamically adjust row color based on status using ANGULAR 4

In my table, I have 6 columns: name, email, phone, company, status_1, and status_2. Both status_1 and status_2 can have two options: "1" or "0." My Requirement: I want to change the color of the row based on the following logic: if(status_1 is "1" ...

Utilizing Keyboard Events within the subscribe function of ViewChildren to focus on typing in Angular2 TypeScript

Is there a way to trigger a Keyboard Event on subscribe in ViewChildren used within a button dropdown nested ul li? <!-- language: lang-js --> import { Component, ElementRef, Renderer,ViewChildren,QueryList,AfterViewInit,OnChanges} from '@angu ...