Dynamic add component using gridstack and angular2? Jquery $.parseHTML does not work

柔情痞子 提交于 2019-11-30 17:22:19
yurzui

The easist way to add fancy-button component dynamically might be as follows:

1) Add component to entryComponents array of your module

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, GridStackComponent, FancyButtonComponent ],
  entryComponents: [ FancyButtonComponent ], // <== here
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

2) Get root node from compiled component

constructor(private vcRef: ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver) { }

getRootNodeFromParsedComponent(component) {
  const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
  const ref = this.vcRef.createComponent(componentFactory, this.vcRef.length, this.vcRef.injector);
  const hostView = <EmbeddedViewRef<any>>ref.hostView;
  return hostView.rootNodes[0];
}

3) Use it anywhere

const fancyBoxElement = this.getRootNodeFromParsedComponent(FancyBoxComponent);  
$('#someId').append(fancyBoxElement);

Here's Plunker Example for your case

If you're looking for something more complicated then there are a lot of answers where you can use angular compiler to do it working

tottomotto

You need to use Angular 2’s ViewContainerRef class, which provides a handy createComponent method. The ViewContainerRef can be informally thought of as a location in the DOM where new components can be inserted.

this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);

Here's a working plunker example.

Or you can use the generic HTML outlete from this post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!