不同模块加载的Angular组件不能在动态编译的组件中呈现
创始人
2025-01-09 11:30:39
0

在动态编译的组件中,必须将不同模块中的组件加入到模块中。您可以使用NgModule的imports属性来实现这一点。下面是一个示例:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { AppComponent }  from './app.component';
import { DynamicComponent } from './dynamic.component';
import { OtherModule } from './other.module';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    OtherModule // 加载其他模块
  ],
  declarations: [
    AppComponent,
    DynamicComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

在这个示例中,我们加载了一个名为“OtherModule”的模块,并将其添加到NgModule的imports数组中。然后,在NgModule的declarations数组中添加了一个动态组件,其中包含了来自“OtherModule”的组件。

当我们在动态编译的组件中引用这个NgModule时,我们也可以使用来自“OtherModule”的组件了:

import { NgModule, Compiler, Component, Input, NgModuleRef, OnInit } from '@angular/core';

@Component({
  selector: 'dynamic-comp',
  template: ``
})
export class DynamicComponent implements OnInit{
  @Input() module: NgModuleRef;
  @Input() selector: string;

  constructor(private compiler: Compiler) {}

  ngOnInit() {
    const factory = this.compiler.compileModuleAndAllComponentsSync(this.module);
    const compFactory = factory.componentFactories.find(x => x.selector === this.selector);

    if (compFactory) {
      const component = compFactory.create(this.injector);
      this.container.insert(component.hostView);
    }
  }
}

在这个示例中,我们使用Angular Compiler来编译包含在模块中的组件。然后我们可以通过selector属性指定要渲染的组件。这样,我们就可以在动态编译的

相关内容

热门资讯

热点推荐!wpk猫腻(wEPO... 热点推荐!wpk猫腻(wEPOKE)外挂透明挂辅助工具(透视)安装教程(有挂详情)-哔哩哔哩;玩家必...
透视美元局(来玩德州)外挂透明... 透视美元局(来玩德州)外挂透明挂辅助器安装(辅助挂)竟然真的有挂(2025已更新)(哔哩哔哩);玩家...
一分钟揭秘(扑克王)外挂透明挂... 一分钟揭秘(扑克王)外挂透明挂辅助器(辅助挂)辅助透视(新版有挂)-哔哩哔哩是一款可以让一直输的玩家...
实测教程(wepoke脚本)外... 实测教程(wepoke脚本)外挂透明挂辅助机制(透视)发牌机制(有挂方法)-哔哩哔哩;大神普及一款德...
一起来探讨!德州nzt软件(W... 一起来探讨!德州nzt软件(WEPoke)外挂透明挂辅助挂(透视)2024新版(竟然有挂)-哔哩哔哩...
揭秘攻略(德扑之星隐藏)外挂透... 揭秘攻略(德扑之星隐藏)外挂透明挂辅助挂(透视)软件透明挂(有挂技术)-哔哩哔哩1、不需要AI权限,...
玩家科普(云扑克)外挂透明挂辅... 玩家科普(云扑克)外挂透明挂辅助器(辅助挂)其实是真的有挂(2023已更新)(哔哩哔哩)是一款可以让...
必知教程(德扑输赢)外挂透明挂... 必知教程(德扑输赢)外挂透明挂辅助插件(透视)发牌机制(有挂详细)-哔哩哔哩;《WPK辅助透视》‌:...
玩家必备教程!epoker外挂... 玩家必备教程!epoker外挂(wepOkE)外挂透明挂辅助挂(透视)详细教程(有挂秘笈)-哔哩哔哩...
9分钟了解(wepoke挂)外... 9分钟了解(wepoke挂)外挂透明挂辅助机制(透视)辅助透视(有挂方针)-哔哩哔哩准备好在wepo...