Angular 2 dynamic template url with string variable?

后端 未结 1 1438
無奈伤痛
無奈伤痛 2020-12-05 06:12
 @Component({
  selector: \'bancaComponent\',
  templateUrl: \'{{str}}\'
})
export class BancaComponent implements OnInit {
  str: String;
  constructor(private http         


        
1条回答
  •  有刺的猬
    2020-12-05 06:30

    Try this solution :

    import {
      Compiler, Component, Injector, VERSION, ViewChild, NgModule, NgModuleRef,
      ViewContainerRef, AfterViewInit, OnInit
    } from '@angular/core';
    
    
    @Component({
      selector: 'bancaComponent',
      template: `
        
      `
      // 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) {
      }
    
      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);
          });
      }
    }
    

    Inspired from : Angular 2/4 component with dynamic template or templateUrl

    Official source : https://angular.io/guide/dynamic-component-loader

    0 讨论(0)
提交回复
热议问题