带有字符串变量的 Angular 2 动态模板 url? [英] Angular 2 dynamic template url with string variable?

查看:27
本文介绍了带有字符串变量的 Angular 2 动态模板 url?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

还有别的方法吗?谢谢:)

Is there another way to make it ? Thanks :)

推荐答案

试试这个解决方案:

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 组件或模板网址

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

这篇关于带有字符串变量的 Angular 2 动态模板 url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆