父组件的angular 2访问子组件属性

Ser*_*gey 23 typescript angular

需要访问属性children元素.家长:

<div>
   <shipment-detail #myCarousel ></shipment-detail>
</div>
Run Code Online (Sandbox Code Playgroud)
@Component({
  selector: "testProject",
  templateUrl: "app/partials/Main.html",
  directives: [ShipmentDetail] })
class AppComponent { 
  getChildrenProperty() {
  // I want to get access to "shipment" 
  }
}
Run Code Online (Sandbox Code Playgroud)

儿童:

@Component({
  selector: "shipment-detail",
}) 
export class ShipmentDetail  {
  shipment: Shipment;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*cok 30

请参阅组件交互功能手册.因此,使用@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);
  }
}
Run Code Online (Sandbox Code Playgroud)

Plunker

  • 在RC6指令中已弃用,因此您只需删除指令:[ShipmentDetails] (3认同)
  • 似乎有一个有趣的问题,本周怎么可能做到. (2认同)
  • @MarkRajcok似乎没有因为角度5而w (2认同)

Kom*_*mal 13

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

子组件 - shipdetail.component.ts:

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

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

检查文档:https : //angular.io/guide/component-interaction#parent-calls-an-viewchild