2016-08-11 120 views
0

我需要動態加載模塊內的自定義組件,並儘可能靈活。動態加載模塊內的組件

例如:

-HTML代碼 -

<button id="floating_button" class="floating_button animation_floating_in" (click)="createNewPost('new_post_form_modal')"><i class="material-icons">gesture</i></button> 
     <div class="modal-content" id="loadHere" > 
      <!-- LOAD MY CUSTOM COMPONENT HERE --> 
     </div> 

-TYPE SCRIPT代碼 -

public createNewPost(nomeComponent:any) 
{ 
    // Load dynamically here nomeComponent inside div with id="loadHere" 
} 

有人可以幫我嗎?

+0

你能解決這個問題嗎? –

+0

我嘗試了很多,但動態組件加載器已更改,並且出現了一些錯誤...我認爲它現在不可能...我只是創建不同的模態組件... –

回答

0

您可以動態地創建組件,如下面,

@Component({ 
    selector: "parent", 
    template: `<button id="floating_button" class="floating_button animation_floating_in" (click)="createNewPost('new_post_form_modal')"><i class="material-icons">gesture</i></button> 
    <div class="modal-content" #loadHere > 
     <!-- LOAD MY CUSTOM COMPONENT HERE --> 
    </div>` 
    }) 
    export class ParentComponent { 
     @ViewChild("loadHere", { read: ViewContainerRef }) childContainer: ViewContainerRef; 

    constructor(private viewContainer: ViewContainerRef, private _cr: ComponentResolver) {} 

    createNewPost = (componentName): void => { 
     componentToLoad = 'resolve component here using componentName'; 
     this._cr.resolveComponent(componentToLoad).then(cmpFactory => {    
      this.childContainer.createComponent(cmpFactory); 
     }); 
    } 
    } 

如果你想傳遞一些參數,您可能會看到this

希望這有助於!