构建组件的服务

时间:2018-05-22 02:14:42

标签: angular angular-services

我的circular dependency服务出现@ComponentBuilderService错误,因为我导入的某些组件,即BreakComponentLocationComponent使用此服务并导入此@ComponentBuilderService

我要做的是使用此buildComponents()中的@ComponentBuilderService方法来动态创建组件,问题是某些组件需要使用此buildComponents()在同一服务上构建子组件的方法。

@ComponentBuilderService:

@Injectable()
export class ComponentBuilderService {
    private renderer: Renderer2;
    constructor(private resolver: ComponentFactoryResolver, renderFactory: RendererFactory2) {
        this.renderer = renderFactory.createRenderer(null, null);
    }
    buildComponents(nContainer: ViewContainerRef , elements) {
        // loop through elements creating different components based on element.Type
        elements.forEach((element, idx) => {
            switch (element.Type) {
                case 'break':
                    const breakComponent = nContainer.createComponent(this.resolver.resolveComponentFactory(BreakComponent));
                    console.log(breakComponent.location.nativeElement);
                    break;
                case 'location':
                    const locationComponent = nContainer.createComponent(this.resolver.resolveComponentFactory(LocationComponent));
                    locationComponent.instance.Elements = element.Elements;
                    break;
            }
        });
    }
}

@LocationComponent:

import { Component, AfterContentInit } from '@angular/core';
import { ComponentBuilder } from '../../../shared/services/component-build.service';

@Component({
  selector: 'location',
  template: `<div> some location building </div>`,
  styleUrls: ['./location.component.scss'],
})
export class LocationComponent implements  AfterContentInit {
    Elements;
    constructor(private componentBuilder: ComponentBuilder) { }
    ngAfterContentInit() {
        console.log(this.Elements);
        this.componentBuilder.buildComponents(this.Elements);
    }
}

问题:无论如何都要创建ComponentBuilderService

0 个答案:

没有答案