如何将Angular组件设置为GridStack widget的内容?
解决方案
问题原因
直接传入HTML字符串的方式无法触发Angular的组件编译逻辑,<app-widget>属于Angular自定义组件标签,浏览器本身无法识别,DomSanitizer仅用于处理HTML安全校验,不会执行组件编译,因此无法生效。
实现代码(Angular14+)
修改后的demo.component.ts
import { Component, OnInit, ViewContainerRef, ComponentRef, OnDestroy } from '@angular/core'; import { GridStack } from 'gridstack'; import { WidgetComponent } from './widget.component'; @Component({ selector: 'app-demo', template: '<div class="grid-stack"></div>', }) export class DemoComponent implements OnInit, OnDestroy { // 存储动态创建的组件引用,用于后续销毁 private compRefs: ComponentRef<unknown>[] = []; constructor(private vcr: ViewContainerRef) {} ngOnInit() { const grid = GridStack.init(); // 1. 动态创建WidgetComponent实例 const widgetCompRef = this.vcr.createComponent(WidgetComponent); this.compRefs.push(widgetCompRef); // 2. 拿到组件对应的原生DOM节点 const widgetDom = widgetCompRef.location.nativeElement; // 3. 将DOM节点作为content传入GridStack grid.load([ { content: widgetDom, w: 2, h: 2 }, { content: '<span>Widget (Native)</span>', w: 2, h: 2 } ]); } ngOnDestroy() { // 手动销毁所有动态创建的组件,避免内存泄漏 this.compRefs.forEach(ref => ref.destroy()); } }
兼容Angular14以下版本
如果使用的是Angular14之前的版本,没有ViewContainerRef.createComponentAPI,可使用ComponentFactoryResolver实现:
import { Component, OnInit, ViewContainerRef, ComponentRef, OnDestroy, ComponentFactoryResolver } from '@angular/core'; import { GridStack } from 'gridstack'; import { WidgetComponent } from './widget.component'; @Component({ selector: 'app-demo', template: '<div class="grid-stack"></div>', }) export class DemoComponent implements OnInit, OnDestroy { private compRefs: ComponentRef<unknown>[] = []; constructor( private vcr: ViewContainerRef, private resolver: ComponentFactoryResolver ) {} ngOnInit() { const grid = GridStack.init(); // 使用ComponentFactoryResolver创建组件 const factory = this.resolver.resolveComponentFactory(WidgetComponent); const widgetCompRef = this.vcr.createComponent(factory); this.compRefs.push(widgetCompRef); const widgetDom = widgetCompRef.location.nativeElement; grid.load([ { content: widgetDom, w: 2, h: 2 }, { content: '<span>Widget (Native)</span>', w: 2, h: 2 } ]); } ngOnDestroy() { this.compRefs.forEach(ref => ref.destroy()); } }
注意事项
- 需将
WidgetComponent添加到所属NgModule的declarations数组中;如果是Angular14+的独立组件,需添加到DemoComponent的imports数组中。 - 若需要给动态组件传输入属性,可直接修改组件实例属性:
widgetCompRef.instance.xxxInput = '自定义值';订阅输出事件可直接调用:widgetCompRef.instance.yyyOutput.subscribe(回调函数)。 - 动态创建的组件不会随父组件自动销毁,必须在
ngOnDestroy生命周期中手动销毁所有组件引用,避免内存泄漏。
内容的提问来源于stack exchange,提问作者Peter Holzer
相关产品推荐
相关产品推荐

