Angular 2动态模板url有字符串变量吗?

Del*_*ell 9 typescript angular2-template angular

 @Component({
  selector: 'bancaComponent',
  templateUrl: '{{str}}'
})
export class BancaComponent implements OnInit {
  str: String;
  constructor(private http: Http) { }
  ngOnInit(): void {
  this.str = "./file.component.html";
}
Run Code Online (Sandbox Code Playgroud)

还有另一种方法吗?谢谢 :)

Bou*_*ule 11

尝试此解决方案:

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);
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

灵感来自:Angular 2/4组件,带有动态模板或templateUrl

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

  • @Boulboulouboule我正在研究Angular 5并且它给了我以下错误---错误在./src/app/app.component.ts中找不到模块:错误:无法解析'myTemplateUrl' (3认同)
  • 首先我得到了“错误:Angular JIT 编译失败:'@Angular/compiler' 未加载!”。我通过 `import "@angular/compiler";` 修复了它。然后我得到“错误:组件”未解析:templateUrl:./another-template.component.html。您是否运行并等待resolveComponentResources()'?`。我找不到如何导入/使用 `resolveComponentResources`。您能否提一些建议? (3认同)