将数据传递给动态创建的 angular 个模块和组件

Pass data to dynamically created angular modules and components

我需要将数据传递给动态创建的 angular 模块,例如 id 或 JSON 我的控制器代码是这样的。

逻辑解释 - API 提供页面布局,如果主要模块排在第一位或次要模块(还有更多不能由 ngif 处理)所有模块都有不同的设计primary 和 secondary 没有 n 种样式,这也由 API 决定。 id是决定该页面所有设计的关键

export class MainLayoutComponent implements OnInit {

 modules: any = [
  {
    module: PrimaryModule,
    component: PrimaryLandingPageComponent,
    id: 1
  },
  {
    module: SecondaryModule,
    component: SecondaryLandingPageComponent,
    id: 2
  },
 ];

 constructor(public compiler: Compiler) {  }

 returnCompiledModule(moduleItem) {
   return this.compiler.compileModuleSync(moduleItem);
 }

 ngOnInit() {
   console.log('hello');
 }

}

为什么我这样做是因为我的页面布局是由 API 决定的,每个模块都有不同类型的组件和不同的设计(该代码已被省略)这是我如何在 HTML

中渲染
<ng-container *ngFor="let module of modules">
  <ng-container 
    *ngComponentOutlet="module.component; 
    ngModuleFactory: returnCompiledModule(module.module);">
  </ng-container>
</ng-container>

有什么方法可以通过路由器将数据传递给模块或与其对应的组件 JSON 或 JSON 本身的 id 值,我可能是另一种语法甜味剂缺少,服务或编译器本身我已经被困在这里一段时间了,我们将不胜感激,或者有没有其他方法可以在没有 IVY 的 angular 版本 8 中做到这一点。提前致谢。

为了使用 ngComponentOutlet 将数据传递给动态创建的组件,您可以使用 Injector.

只需将此功能添加到您的 MainLayoutComponent:

getInjector(moduleItem) {
  return Injector.create([
    { provide: Number, useValue: moduleItem.id }
  ], this.injector);
}

并更改其构造函数以注入 Injector 对象:

constructor(public compiler: Compiler, private injector: Injector) {  }

然后 - 正如您在 docs 中看到的那样 - 在 ngComponentOutlet 中您可以通过指定注入器来传递数据,如下所示:

<ng-container *ngFor="let module of modules">
  <ng-container 
    *ngComponentOutlet="module.component; 
                        ngModuleFactory: returnCompiledModule(module.module);
                        injector: getInjector(module);">
  </ng-container>
</ng-container>

现在每个可以动态创建的 Component 类(PrimaryLandingPageComponentSecondaryLandingPageComponent 等)都应该在其构造函数中包含 id 参数您可以根据需要进一步使用:

constructor(id: Number) { 
  // do whatever you need with id value
}

我尚未测试此代码,因此您可能需要解决一些问题,但希望您能理解。