2017-09-22 241 views
1

以下片段與*ngComponentOutlet一起使用來進行顯示。Angular 4 - * 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?

回答

1

角度編譯器讀取您在@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這樣的:

resolveComponentFactory(this.ngComponentOutlet)

this.ngComponentOutlet持有類引用ToDisplayAComponent,所以它成功地與你指定entryComponents匹配什麼:

entryComponents[0] === this.ngComponentOutlet (ToDisplayAComponent) 

然而,在第二個例子中,你不通過類引用,你通過實例,顯然它們不匹配:

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

這就是爲什麼Angular報告在入口組件中沒有找到組件工廠的錯誤。

你試圖做的事情無法完成。您無法將自定義參數傳遞給組件類構造函數,因爲它是在依賴注入上下文中實例化的。所以如果你需要傳遞給定義了提供者的組件類構造函數。

要了解更多有關動態組件讀Here is what you need to know about dynamic components in Angular

+0

只是一個跟進的問題,當我在陣列中添加2次相同的組件是顯示兩次相同的實例? – Thodoris

+0

@Thodoris,不,他們是不同的實例。這與您在模板中指定相同組件兩次幾乎相同 –

+0

非常感謝。你的回答非常明確,寫得很好,但在批准之前,我想跟隨你所說的內容以及閱讀你的博客文章的文檔,因此可能需要幾天時間。 :) – Thodoris