【问题标题】:angular 2 access child component property from parent componentangular 2 从父组件访问子组件属性
【发布时间】:2016-04-14 15:55:02
【问题描述】:

需要访问属性子元素。 家长:

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

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

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

    【讨论】:

    • 太好了,感谢您的解决方案...当我遇到它时,一个提示(对于像我这样的初学者)...访问constructor 中的属性会产生运行时错误,所以ngAfterViewInit()不是随机选择。
    • 在 RC6 指令中已弃用,因此您只需删除指令:[ShipmentDetails]
    • 好像有一个有趣的问题,这周怎么搞。
    • @Karthikv_26,见angular.io/guide/…
    • @MarkRajcok 似乎不喜欢 angular 5
    【解决方案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);
      }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2019-06-15
      • 2019-11-23
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 2019-01-16
      • 2023-03-27
      相关资源
      最近更新 更多