How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

后端 未结 15 2191
忘掉有多难
忘掉有多难 2020-11-21 05:14

I want to dynamically create a template. This should be used to build a ComponentType at runtime and place (even replace) it somewhere inside of the ho

15条回答
  •  不要未来只要你来
    2020-11-21 05:58

    I must have arrived at the party late, none of the solutions here seemed helpful to me - too messy and felt like too much of a workaround.

    What I ended up doing is using Angular 4.0.0-beta.6's ngComponentOutlet.

    This gave me the shortest, simplest solution all written in the dynamic component's file.

    • Here is a simple example which just receives text and places it in a template, but obviously you can change according to your need:
    import {
      Component, OnInit, Input, NgModule, NgModuleFactory, Compiler
    } from '@angular/core';
    
    @Component({
      selector: 'my-component',
      template: ``,
      styleUrls: ['my.component.css']
    })
    export class MyComponent implements OnInit {
      dynamicComponent;
      dynamicModule: NgModuleFactory;
    
      @Input()
      text: string;
    
      constructor(private compiler: Compiler) {
      }
    
      ngOnInit() {
        this.dynamicComponent = this.createNewComponent(this.text);
        this.dynamicModule = this.compiler.compileModuleSync(this.createComponentModule(this.dynamicComponent));
      }
    
      protected createComponentModule (componentType: any) {
        @NgModule({
          imports: [],
          declarations: [
            componentType
          ],
          entryComponents: [componentType]
        })
        class RuntimeComponentModule
        {
        }
        // a module for just this Type
        return RuntimeComponentModule;
      }
    
      protected createNewComponent (text:string) {
        let template = `dynamically created template with text: ${text}`;
    
        @Component({
          selector: 'dynamic-component',
          template: template
        })
        class DynamicComponent implements OnInit{
           text: any;
    
           ngOnInit() {
           this.text = text;
           }
        }
        return DynamicComponent;
      }
    }
    
    • Short explanation:
      1. my-component - the component in which a dynamic component is rendering
      2. DynamicComponent - the component to be dynamically built and it is rendering inside my-component

    Don't forget to upgrade all the angular libraries to ^Angular 4.0.0

    Hope this helps, good luck!

    UPDATE

    Also works for angular 5.

提交回复
热议问题