簡體   English   中英

使用ngComponentOutlet創建動態組件的依賴注入問題

[英]Dependency Injection problem for creating dynamic components with ngComponentOutlet

該項目需要使用ngComponentOutlet指令動態創建組件。 動態組件將通過將數據注入到構造函數中來接收數據。 那么,如何在構造函數中將此數據作為參數傳遞呢?

我創建了一個示例,鏈接為https://angular-lqaeqp.stackblitz.io/load

項目結構為:

  1. HomeComponent-起點

  2. LoadComponents模塊-延遲加載的模塊,其中包含2個組件

    (i)LoadComponents-路線'/ load'的默認設置

    (ii)Component1Component-將由LoadComponents創建的動態組件

LoadComponents具有以下用於創建的代碼:

<ng-container *ngComponentOutlet="component;injector: injectData;"></ng-container>

  1. 內容模型-需要在Component1Component中注入的模型

如果我刪除了注入代碼,則該應用程序將運行,否則將顯示錯誤:

Error: StaticInjectorError(AppModule)[Component1Component -> Content]

目前,我已經通過使用插件“ ng-dynamic-component”解決了項目問題,該插件的工作原理很吸引人。 但是我必須應用Angular的ngComponentOutlet指令。

您正在向組件中注入Content ,因此它應該是可注入的:

@Injectable({
  providedIn: 'root',
})
export class Content {
    @Input() public Code: string;
    @Input() public HTML: string;
}

您固定的StackBlitz

PS。 始終在您的問題中包含令人煩惱的代碼!

服務和組件在Angular中的用途不同

服務是一個廣泛的類別,涵蓋了應用程序需要的任何價值,功能或功能。 服務通常是具有狹窄,明確定義目的的類。 它應該做特定的事情並且做得很好。

Angular將組件與服務區分開來,以提高模塊化和可重用性。 通過將組件的與視圖相關的功能與其他類型的處理分開,可以使組件類更加精簡和高效。

由於您在content.module.ts中使用Injectable裝飾器,因此不應使用@Input裝飾器。 然后不要用新的關鍵字初始化對象。 使用new關鍵字實例化對象用於創建不可注入的對象。 參考: Angular2-調用Constructor()與new關鍵字創建對象?

content.model.ts

import { Injectable } from '@angular/core';    
@Injectable({
  providedIn: 'root',
})
export class Content {
   Code: string ;
   HTML: string;
}

示例: https//stackblitz.com/edit/angular-favvmz

暫無
暫無

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

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