该项目需要使用ngComponentOutlet指令动态创建组件。动态组件将通过将数据注入构造函数来接收数据。那么,我如何将这些数据作为参数传递给构造函数?
我创建了一个样本,链接是https://angular-lqaeqp.stackblitz.io/load
项目结构是:
LoadComponents具有以下用于创建的代码:
<ng-container *ngComponentOutlet="component;injector: injectData;"></ng-container>
如果我删除注入代码然后应用程序工作,否则它显示错误:
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装饰器。然后不要使用新的关键字初始化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;
}