Angular 2+ Create ViewRef from Markup Injected into Dynamic Template

后端 未结 1 1655
抹茶落季
抹茶落季 2021-01-28 09:13

I would like to create a ViewRef from markup that is dynamically inserted into a template. Is this possible based on the following code sample?

template.html

1条回答
  •  抹茶落季
    2021-01-28 10:19

    To create component dynamically inside

    you can do the following:

    Let's say we need to load the following component

    @Component({
      selector: 'dynamic-comp',
      template: `
       

    Dynamic component

    {{ counter }} ` }) export class DynamicComponent { counter = 1; }

    so first add it to declarations and entryComponents array of your @NgModule

      ...
      declarations: [ ..., DynamicComponent ],
      entryComponents: [ DynamicComponent ],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }
    

    after that create

    template.html

    
    
    

    and finally write

    component.ts

    export class AppComponent {
      compRef: ComponentRef;
    
      constructor(private injector: Injector,
                  private resolver: ComponentFactoryResolver,
                  private appRef: ApplicationRef) {}
    
    
      createComponent() {
        const compFactory = this.resolver.resolveComponentFactory(DynamicComponent);
        this.compRef = compFactory.create(this.injector, null, '#forViewRef');
    
        this.appRef.attachView(this.compRef.hostView);
      }
    
      ngOnDestroy() {
        if(this.compRef) {
          this.compRef.destroy();
        }
      }
    }
    

    I use appRef.attachView in order to include dynamic component to change detection cycle

    Plunker Example

    See also

    • Display custom tag in google maps infowindow angular2

    • Angular2 - Component into dynamicaly created element

    • Add a component dynamically to a child element using a directive

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