2

I have 2 components: A home component and a confirmation component (overlay).

When a button is clicked on the home component, it should trigger the confirmation component to open as a Angular CDK Overlay.

The issue is I cannot pass anything from the home component to the confirmation component by a custom injector and injection token as suggested by many others ie. Angular CDK: How to set Inputs in a ComponentPortal

My code on Stackblitz: https://stackblitz.com/edit/angular-overlay-inject

Did I miss something silly in the code? I am keep getting the StaticInjectorError and NullInjectorError.

enter image description here

Thanks a lot first guys.

Home component:

export const OVERLAY_DATA = new InjectionToken<any>("OVERLAY_DATA");

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  constructor(
    public overlay: Overlay,
    public viewContainerRef: ViewContainerRef,
    private injector: Injector
  ) {}

  public onClick() {
    const config = new OverlayConfig({
      hasBackdrop: true,
      scrollStrategy: this.overlay.scrollStrategies.block()
    });
    config.positionStrategy = this.overlay.position()
      .global()
      .centerHorizontally()
      .centerVertically();
    const overlayRef = this.overlay.create(config);
    overlayRef.backdropClick().subscribe(() => {
      overlayRef.dispose();
    });

    const componentPortal = new ComponentPortal(
      HelloComponent,
      this.viewContainerRef,
      this.createInjector('TestDataStringToPass')
    );
    overlayRef.attach(componentPortal);
  }

  private createInjector(dataToPass): PortalInjector {
    const injectorTokens = new WeakMap();
    injectorTokens.set(OVERLAY_DATA, dataToPass);
    return new PortalInjector(this.injector, injectorTokens);
  }
} 

Overlay component:

export class HelloComponent {

  public displayData: any;

  constructor(@Inject("OVERLAY_DATA") public data: any) {
    console.log("OVERLAY_DATA :", data);
    this.displayData = data;
  }
}
tc01
  • 181
  • 4
  • 12

0 Answers0