角色5:组件上的“NullInjectorError:Renderer2没有提供者”

时间:2017-11-17 13:32:56

标签: angular typescript

我喜欢为Angular 5构建自己的UI库。我将自己定位于Angular Material并尝试构建一个简单的按钮Component。在编译时它工作正常但是当我在项目中使用库时,我得到运行时错误NullInjectorError: No provider for Renderer2

我不知道出了什么问题。我是否必须导入特殊模块或其他东西?

下面你会找到我的组件类:

import { FocusMonitor } from "@angular/cdk/a11y";
import { Platform } from "@angular/cdk/platform";
import { ChangeDetectionStrategy, Component, Directive, ElementRef, HostListener, OnDestroy, Renderer2, ViewEncapsulation } from "@angular/core";

/**
 * Base class for further classes.
 */
export class MyButtonBase {
    constructor(public _renderer: Renderer2, public _elementRef: ElementRef) { }
}

@Component({
    moduleId: module.id,
    selector: "button[my-button], button[my-secondary-button]",
    exportAs: "myButton",
    host: {
        "[disabled]": "disabled || null",
    },
    templateUrl: "button.html",
    styleUrls: ["button.css"],
    inputs: ["disabled"],
    encapsulation: ViewEncapsulation.None,
    preserveWhitespaces: false,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyButton extends MyButtonBase implements OnDestroy {

    constructor(renderer: Renderer2, elementRef: ElementRef, private _platform: Platform, private _focusMonitor: FocusMonitor) {
        super(renderer, elementRef);
        this._focusMonitor.monitor(this._elementRef.nativeElement, this._renderer, true);
    }

    public ngOnDestroy(): void {
        this._focusMonitor.stopMonitoring(this._elementRef.nativeElement);
    }

    public focus(): void {
        this.getHostElement().focus();
    }

    private getHostElement(): any {
        return this._elementRef.nativeElement;
    }
}

2 个答案:

答案 0 :(得分:0)

这似乎是webpack的一个问题。从本地文件路径安装时,会发生此错误。当我发布并通过npm安装它时,它可以很好地工作。

答案 1 :(得分:0)

将构造函数(渲染器:Renderer2更新为构造函数(私有渲染器:Renderer2吗?