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

前端之家收集整理的这篇文章主要介绍了具有动态模板或templateUrl的Angular 2/4组件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在努力寻找解决方案.

我有一个具有不同“皮肤”的项目,它们基本上是不同的模板/ 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);

    }

}
你可以这样做:
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);
      })
  }
}

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

阅读Here is what you need to know about dynamic components in Angular了解更多详情.

猜你在找的Angularjs相关文章