如何在Angular 8中使用条件templateUrl动态创建组件?

时间:2019-07-17 10:37:53

标签: angular

我的应用程序需要支持客户端的自定义HTML,因此一个组件可以具有 templateHtml 的两个选项。

import {
  Compiler, Component, Injector, VERSION, ViewChild, NgModule, NgModuleRef,
  ViewContainerRef, AfterViewInit, OnInit, Input
} from '@angular/core';

@Component({
  selector: 'hello',
  template: '<ng-container #dynamicTemplate></ng-container>',
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() id: number;
  @Input() name: string;

  @ViewChild('dynamicTemplate', { read: ViewContainerRef, static: true }) dynamicTemplate: any;

  constructor(private _compiler: Compiler,
              private _injector: Injector,
              private _m: NgModuleRef<any>) {
  }

  ngAfterViewInit() {
    let myTemplateUrl = './hello.component.html';

    if (this.id % 2 == 1) { // if (haveCustomLayout) {
      myTemplateUrl = '../customlayout/hello.component.html';
    }

    const tmpCmp = Component({
      moduleId: "class_"+module.id, templateUrl: myTemplateUrl
    })(class {
    });
    const tmpModule = NgModule({declarations: [tmpCmp]})(class {
    });
    this._compiler.compileModuleAndAllComponentsAsync(tmpModule) // error here
      .then((factories) => {
        const f = factories.componentFactories[0];
        const cmpRef = f.create(this._injector, [], null, this._m);
        cmpRef.instance.name = 'dynamic';
        this.dynamicTemplate.insert(cmpRef.hostView);
      });
  }
}

这是来自compileModuleAndAllComponentsAsync的错误:

  

获取http://localhost:57630/hello.component.html 404(未找到)   错误错误:未捕获(承诺):无法加载/hello.component.html

Here is a demo

0 个答案:

没有答案