Angular 4 - *ngComponentOutlet 需要说明

Angular 4 - *ngComponentOutlet clarification needed

以下代码片段与 *ngComponentOutlet 一起用于显示。


我有以下工作代码:

this.displayComponent({
        'objects':[
                {component: ToDisplayAComponent, expanded: false},
                {component: ToDisplayBComponent, expanded: false}
                ]
    })

然后对象值数组将用 *ngFor 迭代并显示我的组件。

我想要做的是以下不起作用(在数组中传递相同抽象组件的不同实例,这些实例使用不同的属性初始化):

let compA = new ToDisplayAComponent(aProperty);
let compB = new ToDisplayAComponent(anotherPropert);
this.displayComponent({
            'objects':[
                    {component: compA, expanded: false},
                    {component: compB, expanded: false}
                    ]
        });

除了解决我的问题之外,我将不胜感激,我也很感兴趣,会发生什么,上面的代码不起作用。

PS 编译但抛出此错误:

ERROR Error: No component factory found for [object Object]. Did you add it to @NgModule.entryComponents?

Angular 编译器读取您在 @NgModuleentryComponents 中指定的组件并为它们创建工厂。 ngComponentOutlet 指令然后使用 componentFactoryResolver 获取这些工厂,然后创建组件实例。以下是来源的相关代码:

@Directive({selector: '[ngComponentOutlet]'})
export class NgComponentOutlet implements OnChanges, OnDestroy {
  @Input() ngComponentOutlet: Type<any>;

  ngOnChanges(changes: SimpleChanges) {
    ...
const componentFactory=componentFactoryResolver.resolveComponentFactory(this.ngComponentOutlet);
this._componentRef=this._viewContainerRef.createComponent(componentFactory,...)

既然您的第一个示例有效,我假设您已将 ToDisplayAComponentToDisplayAComponent 添加到条目组件中,如下所示:

@NgModule({
   entryComponents: [ ToDisplayAComponent, ToDisplayBComponent ]

所以当 componentOutlet 像这样请求时:

解析组件工厂(this.ngComponentOutlet)

this.ngComponentOutlet 包含一个 class 引用 ToDisplayAComponent,因此它与您在 entryComponents:

中指定的内容成功匹配
entryComponents[0] === this.ngComponentOutlet (ToDisplayAComponent)

但是,在您的第二个示例中,您没有传递 class 引用,而是传递了实例,但显然它们不匹配:

entryComponents[0] !== this.ngComponentOutlet (new ToDisplayAComponent())
                                              ^^^^^

所以Angular报入口组件中找不到组件工厂的错误

你想做的事无法完成。您无法将自定义参数传递给组件 class 构造函数,因为它是在依赖注入上下文中实例化的。因此,如果您需要将某些内容传递到组件中,class 构造函数定义了一个提供者。

要了解有关动态组件的更多信息,请阅读 Here is what you need to know about dynamic components in Angular