在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
时的注入问题。