我有以下
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 {}
如何动态添加花式按钮组件?
动态添加花式按钮组件的简单方法可能如下所示:
原文链接:https://www.f2er.com/angularjs/143115.html1)将组件添加到模块的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?