在模态内部动态加载组件

时间:2016-08-11 15:31:06

标签: twitter-bootstrap angular typescript modal-dialog

我需要在模态中动态加载自定义组件,并使其尽可能灵活。

例如:

-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 CODE -

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

有人能帮助我吗?

1 个答案:

答案 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

希望这会有所帮助!!