When a card is clicked in the parent component, data is sent to the child component in Angular. The card contains an image, name, ID,

How can I pass data from a parent component (nfts) to a child component (main) when a card is clicked? The card contains images, ids, names, and more information.

I've attempted using @Input() but haven't been able to receive the value in the child component. I also tried using EventEmitter, but struggled with passing the value via the variable.emit(value). Is there a better way to achieve this?

nft.html

<app-main [nftId]="ItemClicked"></app-main>
<div class="container">
    <div class="collectionCard" *ngFor="let data of nftData" 
    (click)="getId(data.token_id,data.image_url,data.name)">
        <img src="{{data.image_url}}" alt="nf img" >
        <div class="details">
            <div class="name">
                {{data.name}} 
                <div class="id">#. {{data.token_id}}</div>
            </div>
        </div>
    
        <div class="priceContainer">
            <img src="assets/assets/weth.png" alt="symbol" class="weithImage">
            <div class="price">{{data.traits[0]?.value}}</div>
        </div>
    </div>
</div>

nft.ts

export class NftsComponent implements OnInit {
  nftData:any = [];
  ItemClicked: any = []; 
 
  getdata(){
    fetch('https://testnets-api.opensea.io/api/v1/assets?asset_contract_address=0x617d411DE5a4D5b668EBAa22Edc7bCdbb88285c4&order_direction=desc&offset=0&limit=5')
   .then(response => response.json())
   .then(response => {
     const data = response.assets;
     this.nftData = data;
     console.log(this.nftData);
   })
   .catch(err => console.error(err))
  }

  getId(id:any, img:string, name:string){
    this.ItemClicked = id; 
    this.ItemClicked = img;
    this.ItemClicked = name;
  }
  
  constructor() { }

  ngOnInit(): void {
   this.getdata();
    
  }

main.ts

export class MainComponent implements OnInit {
  @Input() nftId: any;

  constructor() { }


  ngOnInit(){
    console.log(this.nftId);
  }
}

I want to receive data in the main.ts

stackbliz link - https://github.com/HemanthGirimath/nft-cryptoPunk-clone

Answer №1

To resolve the issue, it is necessary to include the ngOnChanges method within the child component

export class MainComponent implements OnInit,OnChanges{
  @Input() nftId:any;

  constructor() { }


  ngOnInit(){
    console.log( this.nftId);
  }

ngOnChanges(change: SimpleChanges) {
    if(change["nftId"]) {
      console.log(change["nftId"]);
    }
  }
}

Answer №2

To start, you must first create an Object

ItemSelected  : any;

setItemId(id:any,img:string,name:string){
    this.ItemSelected.id = id; 
    this.ItemSelected.img = img;
    this.ItemSelected.name = name;
  }

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

Can you explain the functionality of `property IN array` in the TypeORM query builder?

I'm looking to filter a list of entity ids using query builder in an efficient way. Here's the code snippet I have: await this._productRepo .createQueryBuilder('Product') .where('Product.id IN (:...ids)', { ids: [1, 2, 3, 4] ...

Sliding an image from the left side to the right, and then repeating the movement from left to right

I am currently working on a CSS effect for some images. My goal is to have an image appear from the left side, move towards the right side, then reappear from the left and repeat this cycle. I managed to achieve this using the code below: @keyframes sli ...

What is the method for obtaining a dynamic route path within the pages directory in Next.js?

In my code, I have a special Layout component that compares routing queries and displays the appropriate layout based on the query. I'm looking to extend this functionality to handle dynamic routing scenarios, such as invoices/invoice-1. Currently, ...

Struggling to understand the process of retrieving information from an Axios promise

For my current project, I've been experimenting with using Axios to retrieve JSON data from a json-server to simulate a database environment. While I can successfully display the retrieved data within the .then() block of the Axios function, I'm ...

Is it advisable to flag non-(null|undefined)able type arguments as a type error?

Can the function throwIfMissing be modified to only flag test1 as a compiler error? function throwIfMissing<T>(x: T): T { if (x === null || x === undefined) { throw new Error('Throwing because a variable was null or undefined') ...

Display additional content button, dynamic div identification

I've created a small script that includes a "show more" button at the end of displaying 10 entries. Here is the code: <div id="more<?=$lastid;?>"> <a onclick="showmore(<?=$lastid;?>);">More</a> </div> And here ...

The issue arises when DataTable fails to retrieve the ID element following a page transition

I am facing an issue with making ajax calls on focus for each text input. I am able to do it on the first page, during document ready event. However, when I navigate to another page, JavaScript is unable to parse the inputs as they were not created during ...

Adding a class to a different UL tab from the tab div in jQuery tabs - a guide

Looking to implement a tabs navigation using jQuery without the jQuery Tabs UI. Essentially, when a user clicks on a list item, the script selects the list element with data-tab="X" and adds the class current, making the link visible (default op ...

Using jQuery and Ajax to fade in content after all images and other assets have finished loading

I've encountered an issue with loading pages via ajax for users with custom URLs. For example, a profile is usually found at http://example.com/users/Dan, but if a user has a custom URL like http://example.com/DansCustomURL, I need to fetch their desi ...

Tips for boosting ViteJs development mode performance

One issue I am facing is the slow server performance during development mode. After starting the server and opening the page in my browser, I have to wait 3–6 minutes for it to load! Initially, ViteJs downloads a small amount of resources, but then the ...

The art of encapsulating JSON response objects in Ember Objects with a deep layer of wrapping

Currently, I am engaged in a project using Ember where I retrieve a complex JSON response in a Route's model function. In the associated template, I exhibit attributes of the response. Some of these attributes allow for specific actions that result in ...

The video in the TypeScript code within the Owl Carousel is not displaying properly - only the sound is playing. The video screen remains stationary

I recently updated my query. I am facing an issue while trying to play a video in Owl Carousal with a button click. The video plays sporadically, and most of the time it doesn't work properly. When playing without the carousel, a single video works fi ...

I am encountering a problem with my Material UI react-swipeable-views while using TypeScript

It seems that there is a mismatch in the version of some components. import * as React from "react"; import { useTheme } from "@mui/material/styles"; import Box from "@mui/material/Box"; import MobileStepper from "@mui/ma ...

Updating the KML data on Google Maps V3 for a fresh look

I recently updated a map from V2 to V3 and I am working on incorporating code to automatically refresh the KML data every 30 seconds. The goal is to update the map with the latest data and display a countdown until the next refresh. Here is an example of ...

The dropdown cannot be disabled because it is being passed as an input parameter

We are currently utilizing PrimeNG along with Angular 15. Scenarios: According to the requirements, we need the ability to disable the PrimeNG dropdown control based on a selection. Problem: The disabled property of <p.dropdown> is not functioning ...

Prevent the SnackBar from extending to full width in case of a smaller window size

Is there a solution to prevent the SnackBar from spanning the entire width of the screen when the window is narrow? ...

What is the best way to showcase data from input fields within a bootstrap modal dialog?

After the user has entered their details and clicks submit, I would like to present the information in a Bootstrap modal with a confirmation button below. This serves as a preview of the data before it is saved to the database. Here's what I have so ...

Having challenges retrieving information from MySQL in AngularJS

As a beginner in angularJS, I am trying to display all customers from MySQL. Here is the code I have written in the controller and service: app.controller('CustomersController', function ($scope, customersService, $http) { init(); function ini ...

Custom styles for PrimeNG data tables

Struggling to style the header of a datatable in my Angular project using PrimeNG components. Despite trying various solutions, I am unable to override the existing styles. Even attempting to implement the solution from this PrimeNG CSS styling question o ...

Unable to access the URL slug within the client component in Next.js version 13

In my upcoming project with Next 13, I have a client-side component that is being rendered under the route /journal/[date] Unfortunately, I'm facing an issue trying to extract the date from the URL. I attempted to use: import { useRouter } from &apos ...