首页 > 解决方案 > 动态渲染角度模板时如何捕获错误

问题描述

我正在创建一个动态组件角度。如何捕捉渲染此组件模板的错误

@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);
      }
    });
  }

如果有任何帮助,我将不胜感激。谢谢

标签: angular

解决方案


通过常春藤渲染解决了这个问题

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;
    }
  }

推荐阅读