“Error: No provider for Overlay!”

◇◆丶佛笑我妖孽 提交于 2019-12-03 23:26:27
Piotr Szczepański

I managed to eliminate this error by adding this to app.module.js:

import {OVERLAY_PROVIDERS} from "@angular/material";

@NgModule({
  imports: [...
  ],
  declarations: [...],
  providers: [OVERLAY_PROVIDERS],
  bootstrap: [...]
})

Edit (May 2018):

OVERLAY_PROVIDERS is now deprecated. use the OverlayModule instead

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

@NgModule({
  imports: [
      OverlayModule
  ],
  declarations: [...],
  providers: [...],
  bootstrap: [...]
})

You should do MaterialModule.forRoot() (see the UPDATE2) that should fix the issue.

FYI That is the base maerial2 setup:

import { MaterialModule, MdIconRegistry, } from '@angular/material';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MaterialModule.forRoot()
  ],
  providers: [MdIconRegistry],
  bootstrap: [AppComponent]
})
export class AppModule { }

See more details here http://iterity.io/2016/10/01/angular/getting-started-with-angular-material-2/

UPDATE1: The official material2 doc has being updated so you might look in to this as well https://material.angular.io/guide/getting-started

UPDATE2: In the latest material2 (from 2.0.0-beta.2 and up) no need to use MaterialModule.forRoot() any more just use MaterialModule instead.

The use of Module forRoot has been deprecated and will be removed in the next release. Instead, just simply import MaterialModule directly:

@NgModule({
    imports: [
        ...
        MaterialModule,
        ...
    ]
...
});

UPFATE3: Starting from version 2.0.0-beta.8 angular material depends on @angular/cdk so you need npm install that as well.

MdTooltipModule.forRoot() should also solve your problem as it also includes providers: [OVERLAY_PROVIDERS].

This is from source:

export class MdTooltipModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: MdTooltipModule,
      providers: OVERLAY_PROVIDERS,
    };
  }
}

For @angular/material version 6 and beyond: import OverlayModule in your root module (e.g. in app.module.ts). Importing in lazy-loaded module doesn't work! Details: https://github.com/angular/material2/issues/10820#issuecomment-386733368

I solved this issue by importing my own MaterialModule, which looks something like this

import { NgModule } from '@angular/core';

import {
  MdButtonModule,
  MdCardModule,
  ...
} from '@angular/material';

@NgModule({
  imports: [
    MdButtonModule,
    MdCardModule,
    ...
  ],
  exports: [
    MdButtonModule,
    MdCardModule,
    ...
  ]
})
export class MaterialModule {}

into the spec file, like so

import { MaterialModule } from 'app/material/material.module';
TestBed.configureTestingModule({
      imports: [MaterialModule],
      ...
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!