Angular 7 NgComponentOutlet: 注入问题
创始人
2024-10-16 19:32:10
0

在Angular 7中,使用NgComponentOutlet指令时遇到注入问题的解决方法是通过手动注入依赖项来解决。下面是一个示例代码,演示了如何解决注入问题:

首先,创建一个DynamicComponent,该组件将作为动态组件注入到另一个组件中:

import { Component, Inject } from '@angular/core';
import { MyService } from './my.service';

@Component({
  selector: 'app-dynamic-component',
  template: `
    

Dynamic Component

{{ myService.data }}

`, }) export class DynamicComponent { constructor(public myService: MyService) {} }

然后,在使用NgComponentOutlet的组件中注入MyService

import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver, Injector } from '@angular/core';
import { MyService } from './my.service';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'app-host-component',
  template: `
    

Host Component

`, }) export class HostComponent { @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef; constructor( private componentFactoryResolver: ComponentFactoryResolver, private injector: Injector, private myService: MyService ) {} ngAfterViewInit() { const factory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent); const componentRef = factory.create(this.injector); this.container.insert(componentRef.hostView); } }

请注意,DynamicComponent的构造函数中将MyService注入为公共属性,以便在模板中使用。在HostComponent中,我们通过在create方法中传入this.injector来手动注入DynamicComponent,以确保MyService在动态组件中可用。

最后,确保在模块中正确提供MyService

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { MyService } from './my.service';
import { HostComponent } from './host.component';
import { DynamicComponent } from './dynamic.component';

@NgModule({
  imports: [BrowserModule],
  declarations: [HostComponent, DynamicComponent],
  providers: [MyService],
  bootstrap: [HostComponent],
})
export class AppModule {}

这样就解决了使用NgComponentOutlet时的注入问题。

相关内容

热门资讯

九分钟辅助!小程序财神十三张祈... 九分钟辅助!小程序财神十三张祈福,一贯真的是有辅助挂(真的有挂)1、小程序财神十三张祈福破解器简单,...
三分钟辅助!创游世界辅助器,好... 三分钟辅助!创游世界辅助器,好像真的是有辅助技巧(竟然有挂)创游世界辅助器能透视中分为三种模型:创游...
七分钟辅助!约局吧作弊,原来是... 七分钟辅助!约局吧作弊,原来是真的有辅助挂(有挂规律)1、约局吧作弊公共底牌简单,约局吧作弊透视插件...
两分钟辅助!微信小程序游戏修改... 两分钟辅助!微信小程序游戏修改器,果然有辅助挂(果真有挂)1、微信小程序游戏修改器破解器简单,微信小...
第7分钟辅助!边锋干橙眼辅助器... 第7分钟辅助!边锋干橙眼辅助器名称,切实真的是有辅助软件(有挂规律)1.边锋干橙眼辅助器名称 选牌创...
5分钟辅助!打两圈绝对有辅助,... 5分钟辅助!打两圈绝对有辅助,确实存在有辅助挂(有挂存在)打两圈绝对有辅助是不是有人用挂微扑克wpk...
第二分钟辅助!宝宝吃吃吃游戏辅... 第二分钟辅助!宝宝吃吃吃游戏辅助,原来是真的有辅助方法(果真有挂)1)宝宝吃吃吃游戏辅助免费钻石:进...
第1分钟辅助!邯郸胡乐修改器,... 第1分钟辅助!邯郸胡乐修改器,切实存在有辅助神器(有挂方略)邯郸胡乐修改器是不是有人用挂微扑克wpk...
四分钟辅助!泸州家乡大二辅助,... 四分钟辅助!泸州家乡大二辅助,本来是真的有辅助插件(有挂方法)1、下载好泸州家乡大二辅助脚本下载之后...
3分钟辅助!湖北逍遥辅助,果然... 3分钟辅助!湖北逍遥辅助,果然是真的有辅助神器(确实有挂)所有人都在同一条线上,像星星一样排成一排,...