2017-02-07 135 views
1

我有一個導航欄,其中有購物車,我有一個查看產品組件,在該組件中可以顯示產品列表並將產品添加到主購物車中。 如何將值傳遞給產品組件的主要組件。因此,我可以將其反映到主要組件的購物車中。如何將數據從一個組件傳遞到另一個組件2

我曾嘗試: 產品組件:

@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); 
    } 

很抱歉我不能粘貼代碼作爲其太大。

主要成分:

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

的問題是與車價值的所有其他HTML元素是product選擇的一部分,在主要成分即是越來越呈現沿:產品列表也。

請建議我如何實現這一點。

+0

我只是不明白問題,但是您沒有關閉「product」標記。 – n00dl3

+0

關於在Angular2中的組件之間傳遞數據有很多問題。只要找他們。 –

+0

對不起,產品實際上是一個錯字,正確關閉 – Rohitesh

回答

0

主要compoent:

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

在組件到你需要得到傳遞的值

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

export class Conponent{ 
    private itemAdded={} 
} 

我希望這一個解決您的問題

1

看一看的official document from Angular2以下是代碼示例 -

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是我爲了更好理解而推薦的一個鏈接。

0

正如評論者所說,這個問題很不明確,但似乎是一個常見問題的重複。爲了顯示你的主要成分您對HTML的具體問題 - 這是因爲你沒有關閉你的產品標籤:

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

另一件事 - 你不使用你的onClick方法都在你的模板。您應該重命名它並將重命名的方法綁定到click指令:

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

是的,我很抱歉,因爲我無法在此處顯示所有代碼。但是,爲了您的理解,我正確地關閉了產品標籤。但是,儘管如此,產品選擇器中的所有其他內容也都得到了顯示。另外,我不需要在這個div中(點擊),我只是想在其中顯示值。 onClick用於產品頁面,每個產品都在一次潛水中,並有按鈕添加到卡片中。就像你在亞馬遜或flipkart上看到的一樣 – Rohitesh

相關問題