gyozo kudor
gyozo kudor

Reputation: 6345

How do I create a custom overlay container for angular material

I've tried to follow this guide.

I have a OverlayContainer subclass

import { OverlayContainer } from '@angular/cdk/overlay';

export class CdkOverlayContainer extends OverlayContainer {
  /**
  * Set the container element from the outside, e.g. from the corresponding directive
  */
  public setContainerElement(element: HTMLElement): void {
    this._containerElement = element;
  }
  /**
   * Prevent creation of the HTML element
   */
  protected _createContainer(): void {
    return;
  }
  
}

and then I have a directive:

import { Directive, ElementRef, Renderer2 } from '@angular/core';
import { CdkOverlayContainer } from './CdkOverlayContainer';
import {OverlayContainer} from '@angular/cdk/overlay';

@Directive({
    selector: '[myCdkOverlayContainer]'
})
export class CdkOverlayContainerDirective {

    constructor(protected renderer: Renderer2, protected elementReference: ElementRef, protected cdkOverlayContainer: OverlayContainer) {
       
        this.renderer.addClass(this.elementReference.nativeElement, 'cdk-overlay-container');
        (<any>this.cdkOverlayContainer).setContainerElement(this.elementReference.nativeElement);
    }
}

app.module.ts

    { provide: OverlayContainer, useClass: CdkOverlayContainer },

Then I add a div with that directive

<div myCdkOverlayContainer>
  ...
</div>

to get the following error:

main.ts:14 TypeError: this.cdkOverlayContainer.setContainerElement is not a function
    at new CdkOverlayContainerDirective (CdkOverlayContainerDirective.ts:13)
    at NodeInjectorFactory.CdkOverlayContainerDirective_Factory [as factory] (CdkOverlayContainerDirective.ts:14)

Any help is appreciated.

Upvotes: 4

Views: 5207

Answers (1)

gyozo kudor
gyozo kudor

Reputation: 6345

Was missing Injectable:

@Injectable({providedIn: 'root'})
export class CdkOverlayContainer extends OverlayContainer {
...

Also @angular/cdk version did not match @angular version in package.json for some reason.

Upvotes: 2

Related Questions