微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Angular 9 中创建动态组件的多种方法

如何解决在 Angular 9 中创建动态组件的多种方法

我正在从事一个项目,我必须在 Angular 9 中动态创建组件。我能够使用多种方法进行相同的工作(必须在 buildOptimizer: true 中为所有选项)

选项 1

angular.json
import {
    Component,ComponentFactoryResolver,ComponentRef,ViewContainerRef
} from '@angular/core';

   constructor(private resolver: ComponentFactoryResolver) { }

选项 2

    private createComponentFromraw(template: string,containerRef: ViewContainerRef) {
        const component = Component({ template,styles: [] })(class {
            onClick(item: any) {
                console.log(resource);
            }
        });
        const componentFactory = this.resolver.resolveComponentFactory(component);
        containerRef.clear();
        return containerRef.createComponent(componentFactory);
    }

import {
    ChangeDetectionStrategy,ElementRef,Injector,ɵcompileComponent,ɵrenderComponent,ɵLifecycleHooksFeature
} from '@angular/core';
    constructor(private injector: Injector) { }

有人能帮我理解这两种方法间的区别吗?我最初假设 private createComponentFromraw(template: string,containerRef: ElementRef) { class DynamicComponent { onClick(item: any) { console.log(resource); } } ɵcompileComponent(DynamicComponent,{ template,changeDetection: ChangeDetectionStrategy.OnPush }); ɵrenderComponent(DynamicComponent,{ host: containerRef.nativeElement,injector: this.injector,hostFeatures: [ɵLifecycleHooksFeature],}); } 可以与 ɵcompileComponent 一起使用,因为它是作为 ivy 的一部分引入的,但看起来并非如此。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。