Reputation: 175
I am using ngx-popover, when try to open it from another component it was showing the following error Cannot read property 'show' of undefined below is the following code. home.html is the parent component In
home.html
<button (click)="onShowPopOver()">Device</span>
<device-popover *ngIf="showPopover"></device-popover>
home.component.ts
onShowPopOver() {
this.showPopover=true;
}
and my devicePopover component looks follows
@ViewChild('myPopover') popover: Popover;
constructor() {
this.popover.show();
}
and my devicePopover.html looks as follows:
<popover-content #myPopover class="myPopover"
title="Add/remove an Emulator"
placement="bottom"
[animation]="true"
[closeOnClickOutside]="true" >
<span>Hello</span>
</popover-content>
device-popover is my selector for devicePopover component. when i try to call the child component it was hitting the constructor but throwing the error as "show of undefined"
Upvotes: 0
Views: 1807
Reputation: 21574
@ViewChild refer to a child View, and this view is not created yet when your component is instanciated. You need to rely on a lifecycle hook to be able to access this popover
property:
According to the docs :
ngAfterViewInit()
Respond after Angular initializes the component's views and child views.Called once after the first ngAfterContentChecked().
A component-only hook.
@ViewChild()
will get populated just before ngAfterViewInit
is called.
You also need to put a template reference on your element if you want to use a string as argument to @ViewChild()
:
@ViewChild("myPopover")
<div popover #myPopover=popover *ngIf="showPopover"></div>
otherwise you should use a class as argument :
@ViewChild(Popover) //the popover from ngx-popover, not yours
<div popover *ngIf="showPopover"></div>
So this should work :
@ViewChild("myPopover") popover: Popover;
ngAfterViewInit() {
this.popover.show();
}
<div popover #myPopover=popover *ngIf="showPopover"></div>
Upvotes: 3