Angular 2/4 component with dynamic template or templateUrl

前端 未结 2 855
余生分开走
余生分开走 2020-11-29 05:30

I have been trying to find a solution for this everywhere.

I have a project with different \'skins\', which are basically different sets of templates/Css.

I

2条回答
  •  感动是毒
    2020-11-29 06:02

    You can do it like this:

    import {
      Compiler, Component, Injector, VERSION, ViewChild, NgModule, NgModuleRef,
      ViewContainerRef
    } from '@angular/core';
    
    
    @Component({
      selector: 'my-app',
      template: `
          

    Hello {{name}}

    ` }) export class AppComponent { @ViewChild('vc', {read: ViewContainerRef}) vc; name = `Angular! v${VERSION.full}`; constructor(private _compiler: Compiler, private _injector: Injector, private _m: NgModuleRef) { } ngAfterViewInit() { const tmpCmp = Component({ moduleId: module.id, templateUrl: './e.component.html'})(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.vc.insert(cmpRef.hostView); }) } }

    Just make sure that the URL is correct and the template is loaded into the client.

    Read Here is what you need to know about dynamic components in Angular for more details.

提交回复
热议问题