Search code examples
javascriptangularionic-frameworkangular2-routingng2-bootstrap

Angular2 ng2-popover hide() is not working


app.module.ts

import { PopoverModule } from 'ng2-popover';
@NgModule({
  declarations: [ ...],
  imports: [PopoverModule],
  providers: []
})

example.html

<a [popover]="customPopover" [popoverOnHover]="true" [popoverCloseOnMouseOutside]="true" href="www.google.com" (click)="$event.stopPropagation()" target="_blank">{{name}}</a>
    <!--Popover content -->
    <popover-content #customPopover title="{{name}}" placement="right" 
      [closeOnClickOutside]="true" [closeOnMouseOutside]="true">
      <span class="popoverDesc">{{description}}</span><br /><br />
      <a href="{{websiteLink | formatUrl:'url'}}" (click)="$event.stopPropagation()" target="_blank">{{websiteLink | formatUrl:'text'}}</a><br /><br />
      <button class="btn btn-secondary popoverBtn" (click)="toggleAddToListModalPopover($event)">Add to list</button>
     </popover-content>

example.component.ts

import { PopoverContent } from 'ng2-popover';

@ViewChild('customPopover') customPopover: PopoverContent;

protected toggleAddToListModalPopover(e):void {
  this.customPopover.hide();
  this.showAddToListModal = !this.showAddToListModal;
  e.stopPropagation();
}

I want hide the popover when modal opens. When I call the 'customPopover.hide()' function it gives me error:

error_handler.js:51 TypeError: Cannot read property 'hide' of undefined

at PopoverContent.hide (PopoverContent.js:78)

In 'PopoverContent.js' file there is line this.popover.hide(); but I have no idea how to initialize it. As my understanding is @ViewChild only initializes the class bind to #customPopover i.e. in my case popover-content. Can someone please give me a solution to initialize the 'Popover'?


Solution

  • I think in your case, this.customPopover is undefined.

    Other way you can hide your popover-content like this-

      <div>
        <popover-content #myPopover title="this header can be omitted" placement="right" [closeOnClickOutside]="true">
          <b>Very</b> <span style="color: #C21F39">Dynamic</span> <span style="color: #00b3ee">Reusable</span>
          <b><i><span style="color: #ffc520">Popover With</span></i></b> <small>Html support</small>. Click outside of this popover and it will be dismissed automatically.
    
          <u (click)="myPopover.hide()">Or click here to close it</u>.
        </popover-content>
    
        <button [popover]="myPopover">click this button to see a popover</button>
      </div>
    

    See if this helps.