Angular 2.0 final: How to instantiate a component from code

后端 未结 4 883
[愿得一人]
[愿得一人] 2021-02-05 16:36

I\'m looking for a way to instantiate a component in Angular2 from within the code of another component. Unlike the many people that have asked a similar question I\'m not so mu

4条回答
  •  有刺的猬
    2021-02-05 17:01

    There seems to be a (new?) API function for doing what is described in mxii's answer. The ViewContainerRef has the createComponent method. It instantiates the component and adds it to the view.

    let factory = this._cmpFctryRslvr.resolveComponentFactory(AnyComponent);
    let cmp = this.viewContainer.createComponent(factory);
    cmp.instance.name = 'peter';
    

提交回复
热议问题