簡體   English   中英

Angular - 將mat對話框封裝到模塊中

[英]Angular - encapsulate a mat-dialog to a module

我有一個對話框,我想在我的應用程序的不同部分分享。 不同模塊中的不同組件都應該能夠觸發相同的對話框以及隨之而來的邏輯。 與對話框交互的邏輯嵌入在服務中,該服務還處理如何處理用戶的輸入。 通過調用服務的方法來調用該對話框。

此對話框組件未在應用程序級別聲明業務。 這是不好的封裝。 該對話框只能由服務訪問,因此只應對服務可見。 因此,我應該在與服務相同的模塊中聲明它。

我在我的模塊中聲明並導出了組件,如下所示:

@NgModule({
  imports:      [ ... ],
  declarations: [ NewItemComponent ],
  exports:      [ NewItemComponent ]
})
export class SharedServicesModule {
  static forRoot(): ModuleWithProviders {
    return { 
      ngModule: SharedServicesModule,
      providers: [ ... ]
    }
  }
}

我在app.module.ts引用它,如下所示:

@NgModule({
  declarations:    [ ... ],
  imports:         [ SharedServicesModule.forRoot(), ... ],
  entryComponents: [ NewItemComponent ],
  bootstrap:       [ AppComponent ]
})

不幸的是,這似乎不起作用。

ERROR Error: No component factory found for NewItemComponent. 
Did you add it to @NgModule.entryComponents?

我嘗試在模塊級別將其添加到entryComponents 二者皆是。 甚至通過服務消耗對話的模塊。 無濟於事。

使這項工作的正確方法是什么?

或者我遇到過這個問題: https//github.com/angular/angular/issues/14324

我不知道它是否是理想的解決方案,但我找到了解決方案。 我不明白為什么這樣可行,而我之前嘗試過的卻沒有,但我有工作代碼,所以我會不管它...

我創建了一個獨立的模塊來保存對話框組件,其中包括entryComponents條目,如下所示:

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    MaterialDesignModule
  ],
  declarations:    [ NewItemDialogComponent ],
  exports:         [ NewItemDialogComponent ],
  entryComponents: [ NewItemDialogComponent ]  // <-- NOTICE!
})
export class NewItemDialogModule { }

然后我將該模塊導入到將要使用它的模塊中:

@NgModule({
  imports: [
    CommonModule,
    NewItemDialogModule   // <-- HERE
  ]
})
export class SharedServicesModule { 
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedServicesModule,
      providers: [ ... ]      
    };
  }
}

我沒有必要將對話框導入app.module ,這是目標。

如果有人知道為什么它直接在SharedServicesModule它不起作用,請告訴。

您的NewItemComponent位於SharedServicesModule下,

但是你正在entryComponents: [ NewItemComponent ] 這是問題所在。 您應該在SharedServicesModule而不是在AppModule執行此AppModule

SharedServicesModule添加entryComponents: [ NewItemComponent ] ,所以代碼是

@NgModule({
  imports:      [ ... ],
  declarations: [ NewItemComponent ],
  exports:      [ NewItemComponent ],
  entryComponents: [ NewItemComponent ] // it is here in the **SharedServicesModule** 
})

export class SharedServicesModule {
  static forRoot(): ModuleWithProviders {
    return { 
      ngModule: SharedServicesModule,
      providers: [ ... ]
    }
  }
}

entryComponents: [ NewItemComponent ]刪除entryComponents: [ NewItemComponent ] ,因為此組件不在此模塊下。

@NgModule({
  declarations:    [ ... ],
  imports:         [ SharedServicesModule.forRoot(), ... ],
  bootstrap:       [ AppComponent ]
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM