小编All*_*yar的帖子

如何将组件动态添加到服务中的另一个组件

我将动态地将组件与服务中的另一个组件进行比较,首先,在服务工厂中同时对两个组件进行创建,然后创建可以访问ViewContainer的组件。但是无法创建组件!

服务内容:

@Injectable({
    providedIn: 'root'
})
export class ModalService {

    componentRef: ComponentRef<ModalTemplateComponent>;

    constructor(private _modalService: BsModalService,
                private resolver: ComponentFactoryResolver,
                private injector: Injector) {
    }

    open(componentType: any) {

        const contentFactory = this.resolver
            .resolveComponentFactory(componentType);

        const templateFactory = this.resolver
            .resolveComponentFactory(ModalTemplateComponent);

        const componentRef = templateFactory.create(this.injector);
        componentRef.instance.container.createComponent(contentFactory);

this._modalService.show(componentRef.componentType, {class: 'modal-lg', initialState: {data: {test:true}});

    }
}
Run Code Online (Sandbox Code Playgroud)

零件 :

    selector: 'lib-modal-template',
    template: `
        <h1>{{title}}</h1>
        <ng-container #container>
        </ng-container>
    `,
    styleUrls: ['./modal-template.component.css']
})
export class ModalTemplateComponent implements OnInit {

        title:string;
    @ViewChild('container', {read: ViewContainerRef, static: true}) container: ViewContainerRef;
}
Run Code Online (Sandbox Code Playgroud)

例如:

this._modalService.open(NewUserForm,...);

angular angular-dynamic-components

6
推荐指数
1
解决办法
155
查看次数