具有动态模板或templateUrl的Angular 2/4组件

mil*_*erf 8 themes typescript angular

我一直在努力寻找解决方案.

我有一个具有不同"皮肤"的项目,它们基本上是不同的模板/ Css集合.

我试图让我的组件使用基于变量THEME_DIR的皮肤.

不幸的是,我找不到如何实现这一点.我在angular.io上查看了Dynamic Component Loader但没有成功.

我也在这里看了几个答案但没有成功.

有没有人有想法?

这是我到目前为止所尝试的:

import { ComponentFactoryResolver, ViewContainerRef } from '@angular/core';

// @Component({
//     templateUrl: '../../assets/theme/'+THEME_DIR+'/login.template.html',
// })

export class LoginComponent implements, AfterViewInit {


    private log = Log.create('LoginPage');

    constructor(private mzksLsRequestService: MzkLsRequestService,
                private componentFactoryResolver: ComponentFactoryResolver,
                public viewContainerRef: ViewContainerRef) {
    }



    ngAfterViewInit() {
        let componentFactory = this.componentFactoryResolver.resolveComponentFactory(new Component({
            templateUrl: '../../assets/theme/default/login.template.html',
        }));
        let viewContainerRef = this.viewContainerRef;
        viewContainerRef.clear();
        let componentRef = viewContainerRef.createComponent(componentFactory);

    }

}
Run Code Online (Sandbox Code Playgroud)

Max*_*kyi 14

你可以这样做:

import {
  Compiler, Component, Injector, VERSION, ViewChild, NgModule, NgModuleRef,
  ViewContainerRef
} from '@angular/core';


@Component({
  selector: 'my-app',
  template: `
      <h1>Hello {{name}}</h1>
      <ng-container #vc></ng-container>
  `
})
export class AppComponent {
  @ViewChild('vc', {read: ViewContainerRef}) vc;
  name = `Angular! v${VERSION.full}`;

  constructor(private _compiler: Compiler,
              private _injector: Injector,
              private _m: NgModuleRef<any>) {
  }

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

只需确保URL正确并将模板加载到客户端即可.

阅读以下是您需要了解Angular中动态组件的更多详细信息.

  • 我明白了,不幸的是我对此并不熟悉.我认为你应该创建另一个问题,因为它与我回答的那个问题没有关系 (2认同)