简体   繁体   中英

How to Pass the data from one component to another angular2

I have a navigation bar in which i have cart , and i have a view product component in which i can show the list of the product and add the product into the main cart . How can i pass the value to the main component from the product component.So, that i can be reflected in the cart of main component.

I have tried: Product Component:

    @Component({
      selector:'product',
      template:'Poduct List is getting rendered here and here is a 
      button by clicking the button onClick() method will be called
      and item added into service .This whole template is running in for loop'
    })

    @Input itemAdded:number;

    onClick()
    {
     itemAdded++;
     service.setCartItem(itemAdded);
    }

Sorry i could not able to paste the code as its too big.

Main Component:

<div class="cart"><product [itemAdded]="valueCommingfromService"></div>

The problem is along with the cart value all other html element that is a part of product selector is getting rendered in the main component ie: the product list also.

Please suggest me how i can achive this.

Have a look at the official document from Angular2 Below is the code sample -

import { Component, Input } from '@angular/core';
import { Hero } from './hero';

@Component({
  selector: 'hero-child',
  template: `
   <h3>{{hero.name}} says:</h3>
   <p>I, {{hero.name}}, am at your service, {{masterName}}.</p>`
})
export class HeroChildComponent {
  @Input() hero: Hero;
  @Input('master') masterName: string;
}

Here is one more link which I recommend for better understanding.

Main compoent :

<div class="cart"><product [itemAdded] ="passthevaluehere" /></div>

In the component to which you need to get the passed value

@Component({
  inputs:["itemAdded"]
})

export class Conponent{
  private itemAdded={}
}

I hope this one solve your issue

As commenters have suggested, the question is very unclear but appears to be a duplicate of a frequently asked question. To your specific question regarding html being displayed in your main component - this is because you didn't close your product tag:

<div class="cart"><product [itemAdded]="valueCommingfromService"></product></div>

Another thing - you aren't using your onClick method at all in your template. You should rename it and bind the renamed method to the click directive:

<div class="cart"><product [itemAdded]="valueCommingfromService" (click)="myMethod()"></product></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM