3

我正在尝试templateUrl基于在 @Component 之前导入的模块属性进行设置,即 -

import { details } from './details';

@Component({
  selector: 'app-my-cmp',
  templateUrl: details.typeA ? './pageA.html' : './pageB.html'
})

当我这样做时,我得到了一个错误 - Module not found,但是当我在里面使用导入的模块时,ngOnInit()我可以访问这个模块。

如何templateUrl在行中使用导入的模块?

4

1 回答 1

2

只是另一种解决方案。

您可以使用它来实现这一点ng-template,然后根据您的情况动态更新模板,如下所示 -

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

@Component({
  selector: 'my-app',
  template: `<ng-container #vc></ng-container>`,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  @ViewChild('vc', {read: ViewContainerRef}) vc;
  conditionValue = 'myCondition';

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

  }
  ngOnInit() {
    let tmpCmp;
    if (this.conditionValue === 'myCondition') {
      tmpCmp = Component({
        templateUrl: './e.html'})(class {
      });
    } else {
      // something else
    }

    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);
      })
  }
}

#例子

有关更多信息,请参阅 -

于 2018-11-21T11:59:26.957 回答