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

标签 angular typescript angular2-template

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

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

最佳答案

尝试这个解决方案:

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 2 动态模板 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47133024/

相关文章:

Angular 2(或 4)对象序列化

javascript - RxJS:如何切换多个行为主题源

Angular2 没有提供渲染器! (NgModel -> token NgValueAccessor -> DefaultValueAccessor -> 渲染器)

javascript - 如何以 Angular 组合单一形式的两个部分?

javascript - 使用 Firebase,firebase.auth().currentUser 是 null 值,即使它正在被记录

javascript - 如何将数组从 observable 映射到另一个数组

angular - 检查用户是否已滚动到 Angular 2 的底部

javascript - Angular 2 路由 : Referencing Variable in Router. url

angular - 在 Angular CLI 中使用 angular-in-memory-web-api

javascript - 从 localStorage Typescript/JavaScript 中提取用户名