【问题标题】:How to access view reference of parent component from child component in angular2如何从angular2中的子组件访问父组件的视图引用
【发布时间】:2016-11-26 09:40:33
【问题描述】:

我的目录结构如下:

我将父组件(app.component)的一些方法分配给它的实例变量如下:

export class AppComponent implements AfterViewInit, AfterContentInit{
  @ViewChild('contentLoginModl') contentLoginModlCon: ElementRef;
  @ViewChild('modlSignToApplyTg') modlSignToApplyTg: ElementRef;
  @ViewChild('uploadCV') uploadCV: ElementRef;
  .....
  constructor(){ .... }
  .....
  ngAfterViewInit() {
    this.appState.set('opnLgnAppTmp',this.contentLoginModlCon);
    this.appState.set('opnUpldCvAppTmp',this.uploadCV);
    this.appState.set('opnLgnBfrAppTmp',this.modlSignToApplyTg);
  }

appState(服务)通过所有组件共享,但是当我在子组件中调用访问父视图引用的函数时,它未定义如下:

TypeError: Cannot read property 'open' of undefined
    at AppState._state.open (http://localhost:5003/static/main.prod.bundle.js:6:3788)
    at AppComponent.opnWithTry (http://localhost:5003/static/main.prod.bundle.js:2:17395)
    at AppComponent.opnLgnBfrApp (http://localhost:5003/static/main.prod.bundle.js:2:2714)
    at EditProfile.starItm (http://localhost:5003/static/main.prod.bundle.js:7:14899)
    at View_EditProfile26.handleEvent_24 (/AppModule/EditProfile/component.ngfactory.js:2700:51)
    at HTMLAnchorElement.<anonymous> (http://localhost:5003/static/vendor.prod.bundle.js:27:22958)
    at ZoneDelegate.invokeTask (http://localhost:5003/static/polyfills.prod.bundle.js:4:12265)
    at Object.onInvokeTask (http://localhost:5003/static/vendor.prod.bundle.js:26:14260)
    at ZoneDelegate.invokeTask (http://localhost:5003/static/polyfills.prod.bundle.js:4:12170)
    at Zone.runTask (http://localhost:5003/static/polyfills.prod.bundle.js:4:8197)

【问题讨论】:

    标签: angular dependency-injection angular2-template


    【解决方案1】:

    如果您在构造函数或ngOnInit() 中访问子组件中的状态,那么这是因为尚未执行父组件的ngAfterViewInit() 并且尚未设置属性。

    我建议您使用孩子订阅的可观察对象,并在发出值时收到通知。如果您使用BehaviorSubject,则子级在父级发出属性之前或之后订阅都没有关系。

    另见https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

    【讨论】:

      猜你喜欢
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 2018-01-26
      • 2016-12-02
      相关资源
      最近更新 更多