This is my component from where i'm trying to access a variable in a child component. The parent is the app component and the child is called LoginComponent
import { AfterViewInit, ViewChild } from '@angular/core';
import { Component } from '@angular/core';
import { LoginComponent } from './login/login.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild(LoginComponent)
private loginComponent: LoginComponent;
title = 'app';
hideLogin(){
this.loginComponent.displayPopover = 'none';
}
}
I took this code from this example in the angular.io site The problem is that when the hideLogin() function is executed i get this error:
TypeError: this.loginComponent is undefined
Stack trace:
AppComponent.prototype.hideLogin@webpack-internal:///../../../../../src/app/app.component.ts:21:9
View_AppComponent_0/<@ng:///AppModule/AppComponent.ngfactory.js:10:23
viewDef/handleEvent@webpack-internal:///../../../core/esm5/core.js:13777:115
...
I truncated the error message because i don't think the whole stack trace is of any use. Anyhow, i think the error may be that the loginComponent object is not initialized. But it sound weird to me that the message says "is not defined" and in the example i took it from, it doesn't do anything to initialize the object and somehow it's seems like it has assigned the instance of the component's singleton since it's accessing its properties.
This problem is differen from that in the @viewChild return undefined issue since i'm not trying to access the object from the constructor. I'm trying to access it from a function that is executed via a click event. Here'e my app component view:
<div (click)="hideLogin()">
<app-top-bar></app-top-bar>
</div>
I even tried accessing it from the ngAfterViewInit() method like this:
ngAfterViewInit(){
this.loginComponent.displayPopover = 'none';
}
But i get the same exact error