我有以下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 {}
如何动态添加花式按钮组件?
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示例
如果您正在寻找更复杂的东西,那么有很多答案可以使用角度编译器来完成
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句