錯誤百科

用於啟動的 NgModule 未指定要初始化的元件

這個錯誤表示,一個被用來啟動應用程式的 NgModule,缺少讓 Angular 繼續進行啟動程序的關鍵資訊。

當 @NgModule 註解中缺少 bootstrap 屬性(或是空陣列),且該 NgModule 類別上也沒有定義 ngDoBootstrap 生命週期鉤子時,就會發生這個錯誤。

關於啟動程序的更多資訊,請參閱這份指南。

以下範例都會觸發這個錯誤。

@NgModule({
  declarations: [App],
  imports: [BrowserModule, AppRoutingModule],
  providers: [],
})
export class AppModule {}

// The `AppModule` is used for bootstrapping, but the `@NgModule.bootstrap` field is missing.
platformBrowser().bootstrapModule(AppModule);
@NgModule({
  declarations: [App],
  imports: [BrowserModule, AppRoutingModule],
  providers: [],
  bootstrap: [],
})
export class AppModule {}

// The `AppModule` is used for bootstrapping, but the `@NgModule.bootstrap` field contains an empty array.
platformBrowser().bootstrapModule(AppModule);

如何除錯

請確保用於啟動的 NgModule 有正確設定:

  • @NgModule 註解中存在 bootstrap 屬性(且包含非空的陣列);或
  • NgModule 類別上存在 ngDoBootstrap 方法