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

后端 未结 15 1912
忘掉有多难
忘掉有多难 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:38

    I have a simple example to show how to do angular 2 rc6 dynamic component.

    Say, you have a dynamic html template = template1 and want to dynamic load, firstly wrap into component

    @Component({template: template1})
    class DynamicComponent {}
    

    here template1 as html, may be contains ng2 component

    From rc6, have to have @NgModule wrap this component. @NgModule, just like module in anglarJS 1, it decouple different part of ng2 application, so:

    @Component({
      template: template1,
    
    })
    class DynamicComponent {
    
    }
    @NgModule({
      imports: [BrowserModule,RouterModule],
      declarations: [DynamicComponent]
    })
    class DynamicModule { }
    

    (Here import RouterModule as in my example there is some route components in my html as you can see later on)

    Now you can compile DynamicModule as: this.compiler.compileModuleAndAllComponentsAsync(DynamicModule).then( factory => factory.componentFactories.find(x => x.componentType === DynamicComponent))

    And we need put above in app.moudule.ts to load it, please see my app.moudle.ts. For more and full details check: https://github.com/Longfld/DynamicalRouter/blob/master/app/MyRouterLink.ts and app.moudle.ts

    and see demo: http://plnkr.co/edit/1fdAYP5PAbiHdJfTKgWo?p=preview

提交回复
热议问题