使用gridstack和angular2动态添加组件? Jquery $ .parseHTML不起作用

时间:2016-10-28 22:40:08

标签: angular gridstack

我有以下jsfiddle

我希望能够将自定义组件粘贴到特定网格中(例如"")

现在没有Angular2,我只使用:

var el = $.parseHTML("<div><div class=\"grid-stack-item-content\" data-id=\""+id+"\"/><div/>");
this.grid.add_widget(el, 0, 0, 6, 5, true);

问题是,我不知道我怎么能这样做:

var el = $.parseAndCompileHTMLWithComponent("<div><div class=\"grid-stack-item-content\" data-id=\""+id+"\"/><fancy-button></fancy-button><div/>");
this.grid.add_widget(el, 0, 0, 6, 5, true);

在angular1中,我知道有一个编译,但在angular2中,没有这样的东西。

我的花哨按钮组件很简单,如下所示:

@Component({
  selector: 'fancy-button',
  template: `<button>clickme</button>`
})
export class FancyButton {}

如何动态添加花式按钮组件?

2 个答案:

答案 0 :(得分:5)

动态添加fancy-button组件的简单方法可能如下:

1)将组件添加到模块的entryComponents数组

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

2)从已编译的组件中获取根节点

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)在任何地方使用

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

这是您案例的 Plunker Example

如果您正在寻找更复杂的东西,那么有很多答案可以使用角度编译器来完成它的工作

答案 1 :(得分:1)

您需要使用Angular 2的ViewContainerRef类,它提供了一个方便的createComponent方法。 ViewContainerRef可以被非正式地视为DOM中可以插入新组件的位置。

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

Here's a working plunker example

或者您可以使用this post

中的通用HTML取消删除