来自父组件

时间:2016-04-14 15:55:02

标签: typescript angular

需要访问属性children元素。 父:

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

2 个答案:

答案 0 :(得分:26)

请参阅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

答案 1 :(得分:2)

在新版本的Angular中,我们可以通过在父组件中导入子组件来访问子方法或属性:

子组件-shippingdetail.component.ts:

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

app.component.ts:

import { ShipmentDetailComponent}  from './shipmentdetail.component';   
@Component({
  selector: "testProject",
  templateUrl: "app/partials/Main.html"
})
export class AppComponent { 
  @ViewChild(ShipmentDetailComponent) shipmentDetail:ShipmentDetailComponent;
  ngAfterViewInit() {
      this.getChildProperty();
  }
  getChildProperty() {
     console.log(this.shipmentDetail.shipment);
  }
}

查看文档:{​​{3}}