Angular 2.0 final: How to instantiate a component from code

后端 未结 4 906
[愿得一人]
[愿得一人] 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:03

    In case if anyone wants to avoid any statement in accepted answer here is the snippet

        public createComponent(vCref: ViewContainerRef, type: Type): ComponentRef {
    
          let factory = this._cmpFctryRslvr.resolveComponentFactory(type);
    
          // vCref is needed cause of that injector..
          let injector = ReflectiveInjector.fromResolvedProviders([], vCref.parentInjector);
    
          // create component without adding it directly to the DOM
          let comp = factory.create(injector);
    
          return comp;
        }
    

提交回复
热议问题