Angular 4:ComponentFactoryResolver - 架构建议

时间:2018-04-02 08:08:24

标签: angular typescript

我需要一些关于ComponentFactoryResolver和架构的建议。我的代码中有n个面板(后端提供面板数量),在这些面板中,我有动态字段(后端也提供了数字)。例如,每个面板在开头都应该有4个输入。可以删除或添加字段,具体取决于用户请求。我试图用ComponentFactoryResolver来解决这个问题,我已经陷入了一些困境。

首先,我尝试了两个嵌套循环,一个用于面板,一个用于字段 - 不工作,下面的代码永远不会在页面上呈现。似乎ng模板并没有弄清楚我的动态字段 - 或者我错过了一些东西。

 <div #container *ngFor="let i of [1,2,3]"></div>

其次,我已将代码从HTML移到TypeScript,现在我正在使用AfterViewInit循环,并且我已经设法在我的页面上设置了动态文件 - 但现在我有一个问题,即所有字段都显示在第一个面板中应该是每个面板4个字段...

此外,添加和删除字段的按钮应仅适用于具体面板。例如:如果我点击第二个面板中的第二个添加按钮,我会在第二个面板中显示添加文件。就我而言,这只适用于第一个小组。

  1. 任何想法如何正确解决这个问题,如角度方式?
  2. 我是否正确使用ComponentFactoryResolver?
  3. 为什么第一个使用ngFor循环的解决方案不起作用?
  4. 如何使用ComponentFactoryResolver和ngModel?
  5. 这是否可能,或者我需要完全改变我的策略?
  6. 我不想使用某些ngIf语句并定义一定数量的字段。我想学习解决这类问题的动态和通用方法。

    我做了一个plunker演示: https://plnkr.co/edit/FjCbThpmBmDcgixTpXOy?p=preview

    很抱歉这篇长篇文章。我希望我已经很好地解释了这个问题。 任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我有类似的要求并使用了ComponentFactoryResolver。但是,我在这个ng-template附近放了一个包装器:

@Component({
    selector: 'tn-dynamic',
    template: `<ng-template #container></ng-template>`,
    providers: [SubscriptionManagerService],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class DynamicComponent<T>
    extends DynamicComponentBase<T, T, ComponentData>
    implements OnChanges, OnDestroy {

    @Input()
    set componentData(data: ComponentData) {
        if (!data) {
            return;
        }

        try {
            let type: Type<T> = getComponentType(data.type);

            this._factory = this.resolver.resolveComponentFactory(type);
            let injector = Injector.create([], this.vcRef.parentInjector);
            this._factoryComponent = this.container.createComponent(this._factory, 0, injector);
            this._currentComponent = this._factoryComponent.instance;
    this._factoryComponent.location.nativeElement.classList.add('tn-dynamic-child');

        } catch (er) {
            console.error(`The type ${data.type.library}
.${data.type.key} has not been registered. Check entryComponents?`);
            throw er;
        }
    }

    // Handle ngOnChanges, ngOnDestroy
}

然后我会把我的循环放在我的组件<tn-dynamic [componentData]="myComponentData">

您的componentData包含控件类型,因此您可以使用其他服务根据请求的类型返回正确的类型。

当您开始使用解析器时,不会分配您的输入/输出。所以你必须自己处理。

ngOnChanges(changes: SimpleChanges) {
    let propertyWatch = this.getPropertyWatch();
    for (let change in changes) {
        if (change === propertyWatch) {
            let data = this.getComponentData(changes[change].currentValue);
            if (data) {
                if (data.inputs) {
                    this.assignInputs(data.inputs);
                }

                if (data.outputs) {
                    this.assignOutputs(data.outputs);
                }

                if (this.implementsOnChanges()) {
                    let dynamiChanges = DynamicChanges.create(data);
                    if (dynamiChanges) {
                        (<OnChanges><any>this._currentComponent).ngOnChanges(dynamiChanges);
                    }
                }
            }
        }
    }
}

private unassignVariables() {
    if (this.factory && this.factory.inputs) {
        for (let d of this.factory.inputs) {
            this._currentComponent[d.propName] = null;
        }
    }
}

protected assignInputs(inputs: ComponentInput) {
    for (let key in inputs) {
        if (inputs[key] !== undefined) {
            this._currentComponent[key] = inputs[key];
        }
    }
}

private assignOutputs(outputs: ComponentOutput) {
    for (let key in outputs) {
        if (outputs[key] !== undefined) {
            let eventEmitter: EventEmitter<any> = this._currentComponent[key];
            let subscription = eventEmitter.subscribe(m => outputs[key](m));
            this.sm.add(subscription);
        }
    }
}

然后,我发现使用formControl而不是ngModel来处理表单输入会更好。特别是在处理验证器时。如果您与ngModel保持联系,则无法轻松添加/删除验证程序。但是,创建一个动态组件,[formControl]附加到ComponentFactoryResolver生成的控件似乎是不可能的。所以我不得不动态编译模板。所以我使用另一个服务创建一个控件,如下所示:

const COMPONENT_NAME = 'component';

@Injectable()
export class RuntimeComponent {
    constructor(
        private compiler: Compiler,
        @Optional() @Inject(DEFAULT_IMPORTS_TOKEN)
        protected defaultImports: DefaultImports
    ) {
    }

    protected createNewComponent(tmpl: string, args: any[]): Type<any> {
        @Component({
            selector: 'tn-runtime-component',
            template: tmpl,
        })
        class CustomDynamicComponent<T> implements AfterViewInit, DynamicComponentData<T> {
            @ViewChild(COMPONENT_NAME)
            component: T;

            constructor(
                private cd: ChangeDetectorRef
            ) { }

            ngAfterViewInit() {
                this.cd.detectChanges();
            }
        }

        Object.defineProperty(CustomDynamicComponent.prototype, 'args', {
            get: function () {
                return args;
            }
        });

        // a component for this particular template
        return CustomDynamicComponent;
    }

    protected createComponentModule(componentType: any) {
        let imports = [
            CommonModule,
            FormsModule,
            ReactiveFormsModule
        ];

        if (this.defaultImports && this.defaultImports.imports) {
            imports.push(...this.defaultImports.imports);
        }

        @NgModule({
            imports: imports,
            declarations: [
                componentType
            ],
        })
        class RuntimeComponentModule {
        }
        // a module for just this Type
        return RuntimeComponentModule;
    }

    public createComponentFactoryFromStringSync(template: string, attributeValues?: any[]) {
        let type = this.createNewComponent(template, attributeValues);
        let module = this.createComponentModule(type);

        let mwcf = this.compiler.compileModuleAndAllComponentsSync(module);
        return mwcf.componentFactories.find(m => m.componentType === type);
    }

    public createComponentFactoryFromMetadataSync(selector: string, attributes: { [attribute: string]: any }) {
        let keys = Object.keys(attributes);
        let attributeValues = Object.values(attributes);
        let attributeString = keys.map((attribute, index) => {
            let isValueAFunctionAsString = typeof attributeValues[index] === 'function' ? '($event)' : '';
            return `${attribute}="args[${index}]${isValueAFunctionAsString}"`;
        }).join(' ');

        let template = `<${selector} #${COMPONENT_NAME} ${attributeString}></${selector}>`;
        return this.createComponentFactoryFromStringSync(template, attributeValues);
    }
}

我的代码并不完美,这就是为什么我只给你重要的部分。你必须发挥这个想法,让它按照自己的方式运作。我应该写一篇关于这一天的博文:)

我看了你的plunker,你在使用ngFor时没有正确使用#name。如果你的循环正常工作,你将无法在TypeScript中正确使用它。

此外,您无法在ng-template上执行*ngFor=""。所以你的循环不起作用。见https://toddmotto.com/angular-ngfor-template-element

祝你好运!