javascript - 将数据传递给动态创建的 Angular 模块和组件

标签 javascript angular angular8 angular-router angular-compiler

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

逻辑解释 - 如果主要模块排在第一位或次要模块(还有更多无法由 ngif 处理),API 提供页面布局所有模块都有不同的设计主要和次要没有样式这也由 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 的情况下使用 Angular 版本 8 提前致谢。

最佳答案

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

只需将此函数添加到您的MainLayoutComponent:

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

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

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

然后 - 正如您在 docs 中看到的那样- 在 ngComponentOutlet 中,您可以像这样指定注入(inject)器来传递数据:

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

我没有测试过这段代码,所以您可能需要解决一些问题,但希望您能理解。

关于javascript - 将数据传递给动态创建的 Angular 模块和组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59608781/

相关文章:

javascript - 在 openlayers 中添加弹出信息?

javascript - Laravel/Livewire 在 laravel 混合编译 app.js 中不起作用

javascript - 如何在 Wordpress 中创建添加以进行比较?

redux - 我应该为 angular8 应用程序使用哪个状态管理库?

javascript - 如何将 Mat-Select 值传递到 API 调用中的 header

javascript - 如何使用 Ajax 添加更多过滤器和寻呼机

angular - 验证 ionic2 互联网连接的变化

Angular 6+ :ProvidedIn a non root module is causing a circular dependency

angular - 数据绑定(bind)在 angular2 中不起作用

javascript - 更改后 Angular 8 值不会在 View 中更新