angular 2从父组件类访问子组件对象

时间:2017-08-18 17:26:47

标签: angular typescript

需要访问属性children元素。

父:

<div>
   <shipment-detail #myCarousel ></shipment-detail>
</div>

@Component({
  selector: "testProject",
  templateUrl: "app/partials/Main.html")
class AppComponent { 
  getChildrenProperty() {
  // I want to get access to "shipment" 
  }
}

儿童:

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

1 个答案:

答案 0 :(得分:4)

@ViewChild@ViewChildren装饰器提供对子组件类的访问:

@Component({
    selector: "testProject",
    templateUrl: "app/partials/Main.html")
class AppComponent {

    @ViewChild(ShipmentDetail) ShipDetails: ShipmentDetail;

    getChildrenProperty() {
        console.log(this.ShipDetails.shipment);
    }
}

@ViewChild需要子组件类的名称作为其输入,并在父组件中查找其选择器。

在您的情况下,它应该是ShipmentDetail