【问题标题】:Angular 4: ComponentFactoryResolver - architecture adviceAngular 4:ComponentFactoryResolver - 架构建议
【发布时间】:2018-04-02 18:53:46
【问题描述】:

我需要一些关于 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. 这是否可能,或者我需要完全改变我的策略?

我不想使用一些 ngIf 语句并定义一些字段。我想学习解决此类问题的动态和通用方法。

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

抱歉,帖子太长了。我希望我已经很好地解释了这个问题。 任何建议将不胜感激。

【问题讨论】:

标签: angular typescript


【解决方案1】:

我有类似的要求并使用了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
}

然后我将循环放在我的组件&lt;tn-dynamic [componentData]="myComponentData"&gt;

您的 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 模板上执行 *ngFor=""。所以你的循环只是不工作。见https://toddmotto.com/angular-ngfor-template-element

祝你好运!

【讨论】:

  • 您好,感谢您快速重播。关于 ngFor 和 ng-template,你是对的。但是如果我尝试使用简单的 div 元素也是一样的......
  • 你在一个循环中,你无法触及那个元素。如果你想到达循环中的元素,你可以使用这个技巧:stackoverflow.com/questions/32693061/…
  • 我查看了您的代码,在我看来,我们有一个完全不同的要求。我只使用文本字段作为动态字段,不需要组件类型。这些动态字段总是简单的输入字段 - (总是来自后端的一些字符串,用户也可以输入一些字符串)。也许您可以为我提供一个 plunker 示例以更好地理解您的代码?我试图在我的 plunker 中使用你的代码,但没有运气......
  • 对不起,这是我目前可以分享的最大值。尝试修复你的循环。你会看到,你不能在循环中使用#container。所以你应该有类似tn-dynamic 的东西。那个将有#container。
  • 我已经设法修复了我的循环。但我仍在努力删除归档(它只删除最后一个归档,但它应该删除所有字段)。此外,绑定将非常具有挑战性。我做了一个新的堆栈 blize 示例:stackblitz.com/edit/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-04
  • 2010-11-08
  • 2016-03-16
相关资源
最近更新 更多