angulartypescriptbootstrap-5popoverng-bootstrap

How to pass context properly in ngbPopover?


I can't access context in HTML, although the feature is already there in an official document.

HTML

<button
  type="button"
  class="btn btn-primary"
  triggers="manual"
  #popover="ngbPopover"
  [ngbPopover]="popoverContent"
  [popoverTitle]="'My Popover'"
  (click)="openPopoverWithData()"
>
  Open Popover
</button>

<!-- Popover Content Template -->
<ng-template #popoverContent let-data="context">
  <div *ngIf="data; else noData">
    <strong>Received context:</strong> {{ data | json }}
  </div>
  <ng-template #noData>
    <div>⚠️ No context available</div>
  </ng-template>
</ng-template>

TS

@ViewChild('popover', { static: false }) popover: NgbPopover;

openPopoverWithData() {
  const myContext = {
    id: 1,
    name: 'Test Template'
  };

  // Defensive: ensure popover closes before opening
  if (this.popover.isOpen()) {
    this.popover.close();
  }

  // Open popover with context
  setTimeout(() => {
    this.popover.open(myContext); // 👈 context passed here
  });
}

I also tried with setTimeout, but still it is not working.

I am using "@ng-bootstrap/ng-bootstrap": "^15.1.2" and refer https://ng-bootstrap.github.io/releases/15.x/#/components/popover/api


Solution

  • You should pass the myContext to an object with the property name: context as based on the example: Context and manual triggers.

    this.popover.open({ context: myContext }); // 👈 context passed here
    

    Demo @ StackBlitz