简体   繁体   中英

angular 2 access child component property from parent component

Need to access to property children element. Parent:

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

Children:

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

See the Component Interaction cookbook . So, use @ViewChild() and add a method to ShipmentDetail that the parent can call to retrieve the shipment value, or just access the property directly, as I show below (because I was lazy and didn't want to write an API/method):

@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

In the new version of Angular, we can access child methods or property by importing child component in parent component:

Child component - shipmentdetail.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);
  }
}

Check documentation: https://angular.io/guide/component-interaction#parent-calls-an-viewchild

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM