Angular 2 inject service into dynamic component

I create a multi-step user registration where, after each step, the server returns an HTML string of the following form to complete. At each step, I installed this HTML as a form component template that I dynamically created using CompileService. This works great and the form looks good, but I can’t add any services to this dynamically created form, I keep getting issues like

"Cannot resolve all parameters"

Here is my CompileService

import { Component, ComponentMetadata, ComponentResolver, Injectable, ReflectiveInjector, ViewContainerRef } from '@angular/core';

@Injectable()
export class CompileService {
constructor(private resolver: ComponentResolver) {}

createComponent(metadata: ComponentMetadata, vcRef: ViewContainerRef) {
        let cmpClass = class DynamicComponent {};

        let decoratedCmp = Component(metadata)(cmpClass);
        this.resolver.resolveComponent(decoratedCmp).then(factory => {
        let injector = ReflectiveInjector.fromResolvedProviders(providers, vcRef.parentInjector);
            vcRef.createComponent(factory, 0, injector, []);
        });
    }
}

I want to edit this service so that it not only creates components on the fly, but also can embed services in this component. How can i do this?

+4
source share
1 answer

, ...

let injector = ReflectiveInjector.fromResolvedProviders(providers, vcRef.parentInjector);

, . ...

" "

+1

Source: https://habr.com/ru/post/1652650/


All Articles