1

我已经尝试遵循指南。

我有一个OverlayContainer子类

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;
  }
  
}

然后我有一个指令:

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 },

然后我用那个指令添加一个 div

<div myCdkOverlayContainer>
  ...
</div>

得到以下错误:

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)

任何帮助表示赞赏。

4

1 回答 1

1

失踪了Injectable

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

由于某种原因,@angular/cdk 版本与 package.json 中的@angular 版本不匹配。

于 2020-09-01T09:24:12.420 回答