How to place a dynamic component in a container

前端 未结 3 1120
面向向阳花
面向向阳花 2020-12-01 03:26

I want to create dynamic components and insert views of these components to a container.

I think this can be achieved by ViewContainerRef.

But I don\'t know,

3条回答
  •  自闭症患者
    2020-12-01 03:58

    I was searching for a solution to this problem as well.

    The only way I was able to make it happen was to use an additional Component

    import {Component, ViewContainerRef} from '@angular/core';
    
    @Component({
        selector: 'sw-view-container-ref',
        template: `
    ` }) export class SwViewContainerRef { private _viewContainerRef:ViewContainerRef; constructor(viewContainerRef:ViewContainerRef) { this._viewContainerRef = viewContainerRef; } get viewContainerRef():ViewContainerRef { return this._viewContainerRef; } }

    container.component.ts

    import {Component, ComponentResolver, ViewContainerRef, AfterViewInit, ViewChild,Injector} from '@angular/core'
    import {controlBoxComponent as controlBox} from './controlBox.component';
    import {SwViewContainerRef} from "./sw-view-container-ref";
    
    @Component({
        selector: 'container',
        template: 'container',
        directives: [SwViewContainerRef]
    })
    export class ContainerComponet implements AfterViewInit {
    
        @ViewChild('swViewContainerRef', SwViewContainerRef) swViewChild:SwViewContainerRef;
    
        ngAfterViewInit() {
            this.desiredViewContainerRef = this.swViewChild.viewContainerRef;
    
            var self = this;
    
            this._cr.resolveComponent(controlBox).then((factory) => {
    
                var componentRef = self.desiredViewContainerRef.createComponent(factory, null, self.injector, null);
                componentRef.changeDetectorRef.detectChanges();
                componentRef.onDestroy(()=> {
                    componentRef.changeDetectorRef.detach();
                })
    
                return componentRef;
            });
        }
    
        public desiredViewContainerRef:ViewContainerRef;
    
        constructor(private _cr: ComponentResolver, public injector:Injector) {
    
        }
    }
    

    It should produce something similar to this.

    
    container
    
    controlBox

    I'm not sure if my examples are clear or working, feel free to ask questions or make suggestions, I will try to answer and update my example.

提交回复
热议问题