Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } 
like image 348
Sergey Avatar asked Apr 14 '16 15:04

Sergey


People also ask

How do you access the child component property in the parent component?

We can get child component values in the parent component by creating a reference to the child component using the @ref directive in the Parent component. Using the reference instance, you can access the child component values in the parent.

How do you send value from parent to child component?

Sending data to a child componentlinkThe @Input() decorator in a child component or directive signifies that the property can receive its value from its parent component. To use @Input() , you must configure the parent and child.

How do you pass data from parent component to child component in Angular?

To let Angular know that a property in a child component or directive can receive its value from its parent component we must use the @Input() decorator in the said child. The @Input() decorator allows data to be input into the child component from a parent component.


1 Answers

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

like image 121
Mark Rajcok Avatar answered Sep 17 '22 11:09

Mark Rajcok