使用ngComponentOutlet创建动态组件的依赖注入问题

问题描述 投票:0回答:2

该项目需要使用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指令。

angular angular7
2个回答
1
投票

你正在向你的组件注射Content,因此它应该是一个注射剂:

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

你固定的StackBlitz

PS。始终在您的问题中包含令人不安的代码!


1
投票

服务和组件在Angular中是不同的目的

服务是一个广泛的类别,包含应用程序所需的任何价值,功能或功能。服务通常是具有狭窄,明确定义目的的类。它应该做一些特定的事情,做得好。

Angular将组件与服务区分开来,以提高模块性和可重用性。通过将组件的视图相关功能与其他类型的处理分离,您可以使组件类精简且高效。

由于您在content.module.ts中使用Injectable装饰器,因此不应使用@Input装饰器。然后不要使用新的关键字初始化Object。使用new关键字实例化对象用于创建不可注入的对象。参考:Angular2 - calling constructor() vs new keyword to create an object?

content.model.ts

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

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

© www.soinside.com 2019 - 2024. All rights reserved.