How do I dynamically inject an Angular2 sub component via typescript code?

后端 未结 1 1063
野性不改
野性不改 2021-02-08 19:45

Context - I\'m trying to create a custom dropdown that can contain a number of components. I could accomplish this via the tag, but my team is st

相关标签:
1条回答
  • 2021-02-08 20:23

    You can use the new .createComponent() function.

    import {ComponentRef, Injectable, Component, Injector, ViewContainerRef, ViewChild,ComponentResolver, DynamicComponentLoader} from '@angular/core';
    
    export class InjectComponent {
        @ViewChild('toreplace', {read: ViewContainerRef}) toreplace;   
    
    
        constructor(private dcl: DynamicComponentLoader, injector: Injector,private resolver: ComponentResolver) {}
    

    ...

        this.resolver.resolveComponent((this.createWrapper()).then((factory:ComponentFactory<any>) => {
              this.cmpRef = this.theBody.createComponent(factory)
            });
    

    and remove providers: [DynamicComponentLoader, Injector]

    Here's an example plunker that uses DynamicComponentLoader (in app.component.ts): https://plnkr.co/edit/azoGdAUvDvCwJ3RsPXD6?p=preview

    0 讨论(0)
提交回复
热议问题