2016-04-14 15 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にメソッドを追加して、親が呼び出して出荷値を取得したり、以下に示すようにプロパティに直接アクセスしたりすることができます(私は怠け者で、法):私のような初心者のための

@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

グレート、ソリューションのおかげで... 1つの先端()私はそれに直面したとして... 'それが与えるconstructor'内のプロパティにアクセスランタイムエラーであるため、 'ngAfterViewInit()'はランダムな選択ではありません。 –

+1

RC6ディレクティブは廃止されましたので、ディレクティブを削除するだけです:[ShipmentDetails] –

+2

興味深い質問があるようですが、今週はどうすればいいでしょうか。 – peterh

関連する問題