簡體   English   中英

如何在angular 2中顯示動態添加的組件的列表

[英]How to show a list of dynamically added components in angular 2

利用角度特征動態添加零部件。

文檔

演示

我需要幫助,因此我們直接在頁面上顯示廣告列表,而不是一個接一個地顯示。

我認為這就像在ng-template元素上添加* ngFor一樣簡單,但是似乎比這復雜。

我對angular 2還是比較陌生,因此不勝感激。

將loadComponent函數更改為此:

loadComponent() {
    let viewContainerRef = this.adHost.viewContainerRef;

    for (const ad of this.ads) {
        let componentFactory = this.componentFactoryResolver.resolveComponentFactory(ad.component);
        let componentRef = viewContainerRef.createComponent(componentFactory);
        (<AdComponent>componentRef.instance).data = ad.data;
    }
}

viewContainer一個接一個地插入視圖。

編輯:

關於拋出的錯誤。 最好用一段代碼。 這是對該問題的更詳盡的解釋: https : //blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4

import { ChangeDetectorRef, (...) } from '@angular/core';

constructor(
    private cd: ChangeDetectorRef,
    private componentFactoryResolver: ComponentFactoryResolver
) { }

ngAfterViewInit() {
    this.loadComponent();
    this.getAds();
    this.cd.detectChanges(); 
}

暫無
暫無

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

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