Skip to content

Instantly share code, notes, and snippets.

@navix
Last active July 8, 2019 11:30
Show Gist options
  • Save navix/5cec05d0085bf3311fa0280670772e81 to your computer and use it in GitHub Desktop.
Save navix/5cec05d0085bf3311fa0280670772e81 to your computer and use it in GitHub Desktop.
Component with popup using Angular CDK

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;
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment