加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:47:17 所属栏目:安全 来源:网络整理
导读:我有以下 jsfiddle 我希望能够将自定义组件粘贴到特定的网格中(例如“”) 现在没有Angular2,我只是用: var el = $.parseHTML("divdiv class="grid-stack-item-content" data-id=""+id+""/div/");this.grid.add_widget(el,6,5,true); 问题是,我不知道我
我有以下 jsfiddle

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

现在没有Angular2,我只是用:

var el = $.parseHTML("<div><div class="grid-stack-item-content" data-id=""+id+""/><div/>");
this.grid.add_widget(el,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,true);

在角度1,我知道有一个编译,但在角度2,没有这样的事情.

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

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

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

动态添加花式按钮组件的简单方法可能如下所示:

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你的情况

如果你正在寻找一些更复杂的东西,那么有很多答案可以使用角度编译器去做

> Load existing components dynamically Angular 2 Final Release
> Equivalent of $compile in Angular 2
> How can I use/create dynamic template to compile dynamic Component with Angular 2.0?
> Angular 2.1.0 create child component on the fly,dynamically
> How to manually lazy load a module?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读