我使用ComponentFactoryResolver动态创建组件,并使用ReflectiveInjector动态传递它们.
这看起来很像
@ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;
let inputProviders = [{
provide: 'injectedInput',
useValue: inputValue
}];
let resolvedInputs = ReflectiveInjector.resolve(inputProviders);
let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.container.parentInjector);
let factory = componentInfo.factory.resolveComponentFactory(componentInfo.component);
let component = factory.create(injector);
this.container.insert(component.hostView);
Run Code Online (Sandbox Code Playgroud)
然后动态创建的组件看起来像这样
import {Component, Injector} from '@angular/core';
@Component({
selector: 'mycomponent'
})
export class MyComponent {
private id: string;
constructor(private injector: Injector) {
this.id = injector.get('injectedInput');
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试为使用核心Injector模块的组件编写单元测试.我收到以下错误:
错误:没有injectInput的提供者!
我的spec文件看起来像这样:
import { MyComponent } from 'here';
describe('MyComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
MyComponent …Run Code Online (Sandbox Code Playgroud)