Angular 递归创建动态组件

Ben*_*eng 4 javascript typescript angular

我正在尝试基于配置构建一个动态组件。组件将递归读取配置并创建组件。发现 ngAfterViewInit() 方法只会被调用两次。

@Component({
    selector: "dynamic-container-component",
    template: `
        <div #container
            draggable="true"
            (dragstart)="dragstart($event)"
            (drop)="drop($event)"
            (dragover)="dragover($event)"
            style="border: 1px solid; min-height: 30px"></div>
    `
})
export default class DynamicContainerComponent {

    @Input()
    dynamicConfig: DynamicConfig;

    @ViewChild("container", {read: ElementRef})
    private elementRef: ElementRef;

    private isContainer: boolean;
    private componentRef: ComponentRef<any>;
    private componentRefs: ComponentRef<any>[] = [];
    
    constructor(
        private componentFactoryResolver: ComponentFactoryResolver,
        private injector: Injector,
        private viewContainer: ViewContainerRef,
        private render: Renderer2
    ){
        console.log("running");
    }

    ngAfterViewInit(){
        
        if (this.dynamicConfig){
            console.log(this.dynamicConfig)
            if (this.dynamicConfig.getType() == ComponentType.INPUT){
                this.isContainer = false;
                let componetFactory: ComponentFactory<InputComponent> = 
                    this.componentFactoryResolver.resolveComponentFactory(InputComponent);
                this.componentRef = this.viewContainer.createComponent(componetFactory);
                this.render.appendChild(this.elementRef.nativeElement, this.componentRef.location.nativeElement);
            }else {
                this.isContainer = true;
                let items: DynamicConfig[] = this.dynamicConfig.getItems();
                if (items){
                    for (var i=0; i<items.length; i++){
                        let item: DynamicConfig = items[i];
                        let componetFactory: ComponentFactory<DynamicContainerComponent> = 
                            this.componentFactoryResolver.resolveComponentFactory(DynamicContainerComponent);
                        let componentRef: ComponentRef<DynamicContainerComponent> = 
                            this.viewContainer.createComponent(componetFactory);
                        componentRef.instance.dynamicConfig = item;
                        this.componentRefs.push(componentRef);
                        this.render.appendChild(this.elementRef.nativeElement, componentRef.location.nativeElement);
                    }
                }
            }
        }else {
            console.log("config does not exist");
        }

    }

    dragstart(event){
        debugger;
    }

    drop(event){
        debugger;
    }

    dragover(event){
        debugger;
        event.preventDefault();
    }


}
Run Code Online (Sandbox Code Playgroud)

该组件将由其他组件通过以下代码创建。如果动态组件将通过 componentFactoryResolver 创建另一个动态组件。

    var configJson = {
        type: ComponentType.CONTAINER,
        items: [
            {
                type: ComponentType.CONTAINER,
                items: [{
                    type: ComponentType.CONTAINER,
                    items: [{
                        type: ComponentType.CONTAINER,
                        items: [{
                            type: ComponentType.INPUT
                        }]
                    }]
                }]
            }
        ]
    }

    this.config = new DynamicConfig();
    this.config.assign(configJson);
    console.log(this.config);
Run Code Online (Sandbox Code Playgroud)

更新 我在 github 中发现了一个类似的问题:https : //github.com/angular/angular/issues/10762

我做了一些别人建议的事情。但我认为这只是一个肮脏的修复。

ngAfterViewInit(){
    setTimeout(function(){
        if (this.dynamicConfig){
            console.log(this.dynamicConfig)
            if (this.dynamicConfig.getType() == ComponentType.INPUT){
                this.isContainer = false;
                let componetFactory: ComponentFactory<InputComponent> = 
                    this.componentFactoryResolver.resolveComponentFactory(InputComponent);
                this.componentRef = this.viewContainer.createComponent(componetFactory);
                this.render.appendChild(this.elementRef.nativeElement, this.componentRef.location.nativeElement);
            }else {
                this.isContainer = true;
                let items: DynamicConfig[] = this.dynamicConfig.getItems();
                if (items){
                    for (var i=0; i<items.length; i++){
                        let item: DynamicConfig = items[i];
                        let componetFactory: ComponentFactory<DynamicContainerComponent> = 
                            this.componentFactoryResolver.resolveComponentFactory(DynamicContainerComponent);
                        let componentRef: ComponentRef<DynamicContainerComponent> = 
                            this.viewContainer.createComponent(componetFactory);
                        componentRef.instance.dynamicConfig = item;
                        this.componentRefs.push(componentRef);
                        this.render.appendChild(this.elementRef.nativeElement, componentRef.location.nativeElement);
                    }
                }
            }
        }else {
            console.log("config does not exist");
        }
    }.bind(this))
}
Run Code Online (Sandbox Code Playgroud)

yur*_*zui 5

到您创建动态组件时,angular 几乎已完成更改检测周期。

这样你可以运行:

componentRef.changeDetectorRef.detectChanges()
Run Code Online (Sandbox Code Playgroud)

注意setTimeout具有类似的效果,但会在整个应用程序上触发更改检测周期

将生命周期挂钩重命名为ngOnInit

此外,您将错误的输入传递给动态组件:

let item: DynamicConfig = items[i];
          ^^^^^^^^^^^^^
    but it is not DynamicConfig instance but rather plain object
...
componentRef.instance.dynamicConfig = item;
Run Code Online (Sandbox Code Playgroud)

它应该是:

let item: any = items[i];
const config = new DynamicConfig();
config.assign(item);
componentRef.instance.dynamicConfig = config;
Run Code Online (Sandbox Code Playgroud)

吴运行示例