Component with popup using Angular CDK Overlay
Template:
<ng-template #templateRef>
Popup content
</ng-template>
Component:
export class InPopupComponent implements OnInit {
// Receive anchor reference (where popup will be displayed)
@Input() anchorRef: ElementRef;
// Get template reference
@ViewChild('templateRef') templateRef: TemplateRef<any>;
// Inject required deps
constructor(
private overlay: Overlay,
private vcr: ViewContainerRef,
) {
}
// Show popup
show() {
// Create and configure overlay
this.overlayRef = this.overlay.create({
// Position strategy defines where popup will be displayed
positionStrategy: this.overlay.position()
.flexibleConnectedTo(this.anchorRef)
.withPositions([{
originX: 'center',
originY: 'bottom',
overlayX: 'center',
overlayY: 'top',
}]),
// Popup reposition on scroll
scrollStrategy: this.overlay.scrollStrategies.reposition(),
// Display backdrop
hasBackdrop: true,
});
// Put template to a portal
const periodSelectorPortal = new TemplatePortal(this.templateRef, this.vcr);
// Attach the portal to the overlay
this.overlayRef.attach(periodSelectorPortal);
// Handle closing
merge(
this.overlayRef.backdropClick(),
this.overlayRef.detachments(),
).subscribe(() => {
this.close();
});
}
close() {
if (this.overlayRef) {
this.overlayRef.dispose();
this.overlayRef = undefined;
}
}
}