[英]How to access view reference of parent component from child component in angular2
I have directory structure as follows: 我的目录结构如下:
I assigned some method of parent component(app.component) to instance variable of it as follows: 我为它的实例变量分配了一些父组件(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 (service) is shared through all components but when i'm calling a function inside child compinent which access the refrence of parrent view it comes undefined as follows: 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)
If you access the state in the child component in the constructor or ngOnInit()
then this is because ngAfterViewInit()
of the parent wasn't yet executed and the properties are not yet set. 如果您在构造函数或访问子组件的状态
ngOnInit()
那么这是因为ngAfterViewInit()
母公司尚未执行和性能目前尚未确定。
I'd suggest you use observables the child subscribes to and gets notified when values are emitted. 我建议您使用孩子订阅的观察值,并在发出值时得到通知。 If you use
BehaviorSubject
it doesn't matter if the child subscribes before or after the parent emits the properties. 如果使用
BehaviorSubject
,则子级在父级发出属性之前或之后进行订阅都没有关系。
See also https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service 另请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.