2016-04-14 96 views
7

需要訪問屬性子元素。 家長:角度2訪問父組件的子組件屬性

<div> 
    <shipment-detail #myCarousel ></shipment-detail> 
</div> 
@Component({ 
    selector: "testProject", 
    templateUrl: "app/partials/Main.html", 
    directives: [ShipmentDetail] }) 
class AppComponent { 
    getChildrenProperty() { 
    // I want to get access to "shipment" 
    } 
} 

孩子:

@Component({ 
    selector: "shipment-detail", 
}) 
export class ShipmentDetail { 
    shipment: Shipment; 
} 

回答

15

Component Interaction cookbook。因此,使用@ViewChild()並向ShipmentDetail添加一個方法,父級可以調用它來檢索裝運值,或者直接訪問該屬性,如下所示(因爲我很懶,不想寫一個API /法):

@Component({ 
    selector: "testProject", 
    templateUrl: "app/partials/Main.html", 
    directives: [ShipmentDetail] 
}) 
export class AppComponent { 
    @ViewChild(ShipmentDetail) shipmentDetail:ShipmentDetail; 
    ngAfterViewInit() { 
     this.getChildProperty(); 
    } 
    getChildProperty() { 
    console.log(this.shipmentDetail.shipment); 
    } 
} 

Plunker

+0

大,感謝您的解決方案...一個尖端(對於我這樣的初學者),因爲我面對它...訪問裏面的屬性'constructor'它會給一個運行時錯誤,所以'ngAfterViewInit()'不是一個隨機選擇。 –

+1

在RC6指令已棄用,所以你只需要刪除指令:[ShipmentDetails] –

+2

似乎有一個有趣的問題,這個星期怎麼可能完成。 – peterh

相關問題