angular - 动态渲染角度模板时如何捕获错误
问题描述
我正在创建一个动态组件角度。如何捕捉渲染此组件模板的错误
@ViewChild('vc', { read: ViewContainerRef }) _container: ViewContainerRef;
private insertDynamicComp() {
this._container.clear();
this.generateComponent(this.element.data).then((view) => {
this._container.insert(view);
});
}
private generateComponent(template: string): Promise<ViewRef> {
return new Promise((resolve, reject) => {
try {
const _this = this;
const tmpCmp = Component({
template: template || '',
changeDetection: ChangeDetectionStrategy.OnPush,
})(DynamicClass);
const tmpModule = NgModule({
declarations: [tmpCmp],
})(class {});
const t = this._compiler.compileModuleAndAllComponentsSync(tmpModule);
const f = t.componentFactories[0];
const cmpRef = f.create(this._injector, [], null, this._m);
cmpRef.instance.SetParentFunction(_this);
resolve(cmpRef.hostView);
} catch {
reject(null);
}
});
}
如果有任何帮助,我将不胜感激。谢谢
解决方案
通过常春藤渲染解决了这个问题
import {
ChangeDetectionStrategy,
Component,
ElementRef,
Injector,
OnInit,
ViewChild,
ɵcompileComponent,
ɵrenderComponent as renderComponent,
ɵLifecycleHooksFeature as LifecycleHooksFeature,
ɵmarkDirty as markDirty,
Input,
} from '@angular/core';
const ERROR_TEMPLATE = `
<div style="width:100%; height:100%; border: 1px solid black;border-style:dotted;color: red;font-size: 16px;">
ERROR TEMPLATE: [error]
</div>`;
@ViewChild('div', { read: ElementRef }) _div: ElementRef;
private generateComponent(template: string): IDynamicClass {
try {
class DynamicClass implements IDynamicClass {
api: any = {};
parentObj: AngularTemplateComponent;
mappedValue: IMappedName;
state: ISimpleStetVar;
constructor() {}
public SetParentFunction(parent: AngularTemplateComponent) {
this.parentObj = parent;
this.api = parent;
}
}
this.showErrorTemplate = false;
ɵcompileComponent(DynamicClass, {
template: template || '',
changeDetection: ChangeDetectionStrategy.OnPush,
});
const comp = renderComponent(DynamicClass, {
host: this._div.nativeElement,
injector: this._injector,
hostFeatures: [LifecycleHooksFeature],
});
return comp;
} catch (error) {
this.errorTemplate = this._sanitizer.bypassSecurityTrustHtml(
ERROR_TEMPLATE.replace('[error]', error?.message),
);
this.showErrorTemplate = true;
console.error(error?.message);
return null;
}
}
推荐阅读
- asp.net-mvc - 将 ViewComponent 视图作为 HtmlStrings 返回以在其他 ViewComponents 中进行操作
- python - UnboundLocalError-赋值前引用的局部变量“app”
- javascript - 使用 JS 和 CSS 过渡切换 Flex 的展开和折叠
- linux - 如何让 Jmeter 从 CMD 运行命令 - 操作系统采样器 - JMETER
- c++ - 如何为 Tesseract 构建静态二进制文件?
- php - Composer 不加载文件
- python - Numpy - 比较两个二维数组中的元素并替换值
- php - 如何通过php正则表达式获取data-cfemail标签内的字符串?
- node.js - Git 询问“请告诉我你是谁”。无法自动检测电子邮件地址?
- excel - 检测文本相同但文本格式不同的单元格之间的差异