【问题标题】:Dynamic add component using gridstack and angular2? Jquery $.parseHTML does not work使用gridstack和angular2动态添加组件? Jquery $.parseHTML 不起作用
【发布时间】:2017-03-11 21:08:21
【问题描述】:

我有以下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 {}

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

【问题讨论】:

标签: angular gridstack


【解决方案1】:

动态添加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 适合您的情况

如果你正在寻找更复杂的东西,那么有很多答案可以让你使用 Angular 编译器来完成它

【讨论】:

  • @yuzui 我试过这个例子,我得到 this.componentFactoryResolver.resolveComponentFactory is not a function 错误
  • @rish 你能提供一些 plunker 吗?
  • @rish 如果你想用动态 html 创建组件,那么你必须使用Compiler。我更新了你的 plunker plnkr.co/edit/GDyJk0GGPOF5opax5cwX?p=preview 如你所见,我得到了 HtmlElement 并将其添加到 document.body
  • @yuzui thnx 这对我很有帮助,这里只有一个问题,我们可以在没有 [at]Component 和 [at]Directives 的普通类中创建这两个方法吗?
【解决方案2】:

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

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

Here's a working plunker example.

或者您可以使用来自this post 的通用 HTML 插座

【讨论】:

  • 有很多 DynamicComoponentLoader 线程,但这些答案不相关,因为它已被弃用。
猜你喜欢
  • 2017-11-28
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 2014-02-25
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多