4

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

逻辑解释 - API 提供页面布局,如果主要模块是第一个或次要模块(还有更多无法由 ngif 处理)所有模块都有不同的设计主要和次要没有样式,这也由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 中的 id 值或 JSON 本身,我可能缺少的另一种语法甜味剂,服务或编译器本身我一直被困在这里有时任何帮助将不胜感激,或者是否有任何其他方法可以在没有 IVY 的角度版本 8 中做到这一点提前致谢。

4

1 回答 1

3

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

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

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

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

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

然后 - 正如您在文档中看到的那样- 在内部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现在,可以动态创建的每个类(PrimaryLandingPageComponent等)都应该在其构造函数中SecondaryLandingPageComponent包含参数,您可以根据需要进一步使用:id

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

我没有测试过这段代码,所以你可能需要修复一些问题,但希望你能明白。

于 2020-01-06T09:15:05.650 回答