【问题标题】:Angular 2 dynamic template url with string variable?带有字符串变量的Angular 2动态模板url?
【发布时间】:2025-12-20 18:00:07
【问题描述】:
 @Component({
  selector: 'bancaComponent',
  templateUrl: '{{str}}'
})
export class BancaComponent implements OnInit {
  str: String;
  constructor(private http: Http) { }
  ngOnInit(): void {
  this.str = "./file.component.html";
}

还有其他方法吗? 谢谢:)

【问题讨论】:

    标签: angular typescript angular2-template


    【解决方案1】:

    试试这个解决方案:

    import {
      Compiler, Component, Injector, VERSION, ViewChild, NgModule, NgModuleRef,
      ViewContainerRef, AfterViewInit, OnInit
    } from '@angular/core';
    
    
    @Component({
      selector: 'bancaComponent',
      template: `
        <ng-container #dynamicTemplate></ng-container>
      `
      // or with a templateUrl
    })
    export class BancaComponent implements AfterViewInit, OnInit {
      @ViewChild('dynamicTemplate', {read: ViewContainerRef}) dynamicTemplate;
    
      constructor(private _compiler: Compiler,
                  private _injector: Injector,
                  private _m: NgModuleRef<any>) {
      }
    
      ngAfterViewInit() {
        let myTemplateUrl = './file.component.html';
    
        if (MYCONDITION === MAEXPECTATION) {
          myTemplateUrl = './another-template.component.html';
        }
    
        const tmpCmp = Component({
          moduleId: module.id, templateUrl: myTemplateUrl
        })(class {
        });
        const tmpModule = NgModule({declarations: [tmpCmp]})(class {
        });
    
        this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
          .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);
          });
      }
    }
    

    灵感来自:Angular 2/4 component with dynamic template or templateUrl

    官方来源:https://angular.io/guide/dynamic-component-loader

    【讨论】:

    • 错误是什么?看看 angular 官方对这类问题的解决方案:angular.io/guide/dynamic-component-loader
    • @Boulboulouboule 我正在研究 Angular 5,它给了我以下错误 --- ./src/app/app.component.ts 中的错误模块未找到:错误:无法解析' myTemplateUrl'
    • 有人能够解决 Angular 5+ 版本中的错误吗?
    • 角度 9 出现此错误:screencast.com/t/HgRuD3fKD
    • 首先我得到了Error: Angular JIT compilation failed: '@angular/compiler' not loaded!。我通过import "@angular/compiler"; 修复了它。然后我得到了Error: Component '' is not resolved: templateUrl: ./another-template.component.html. Did you run and wait for resolveComponentResources()'?。我找不到如何导入/使用resolveComponentResources。可以请教吗?