简体   繁体   English

如何使用Angular2中的组件呈现动态模板

[英]How to render a dynamic template with components in Angular2

I've tried many stackoverflow options like Load existing components dynamically Angular 2 Final Release . 我已经尝试了很多stackoverflow选项,例如动态加载现有组件Angular 2 Final Release

What i want to do is get a html page with a ajax request and render/compile this template in my custom component. 我想要做的是获取一个带有ajax请求的html页面,并在我的自定义组件中呈现/编译此模板。

I've figured out that angular2 has two deprecated components and that i have to use ComponentFactoryResolver . 我已经发现angular2有两个不赞成使用的组件,我必须使用ComponentFactoryResolver

In my old solution i could just set a '[innerHtml]' to render the HTML. 在我的旧解决方案中,我可以设置'[innerHtml]'来呈现HTML。 Now i need a new solution. 现在我需要一个新的解决方案。

Who can help me out? 谁能帮助我?

page.component.ts page.component.ts

import { Component, ViewChild, ViewContainerRef, ComponentFactory, OnInit, ComponentFactoryResolver } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';


@Component({
    selector: "wd-page",
    templateUrl: "/app/page/page.component.html",
    providers: []
})
export class PageComponent implements OnInit {

    // we need the viewcontainer ref, so explicitly define that, or we'll get back
    // an element ref.
    @ViewChild('dynamicChild', { read: ViewContainerRef })
    private target: ViewContainerRef;

    private page = {
        Source: "<div><h2>Hello world</h2><one-of-my-components></one-of-my-components></div>"
    }


    constructor(
        private vcRef: ViewContainerRef,
        private resolver: ComponentFactoryResolver) { }


        ngOnInit() {
            //What code do i need here?
        }
}
<div #dynamicChild></div>

<!-- Old implementation!

    <div *ngIf="!showSource" [innerHTML]="page">
    </div>
-->

Problem solved Thanks to Yurzui, 问题解决了感谢Yurzui,

https://plnkr.co/edit/TAbupH4si62x10QZ7xuc?p=preview https://plnkr.co/edit/TAbupH4si62x10QZ7xuc?p=preview

The generic HTML outlete from a different post ( Angular 2.1.0 create child component on the fly, dynamically ) can be used to render templates with custom directives in them. 来自不同帖子的通用HTML outlete( Angular 2.1.0动态创建子组件,动态 )可用于呈现带有自定义指令的模板。

Don't forget to import a module with all the custom components that you want to render! 不要忘记导入包含要渲染的所有自定义组件的模块

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
const cmpClass = class DynamicComponent {};
const decoratedCmp = Component(metadata)(cmpClass);

// Import the module with required components here
@NgModule({ imports: [CommonModule, RouterModule, SharedModule], declarations: [decoratedCmp] })
class DynamicHtmlModule { }

return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
   .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
    return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
  });
}

I made tiny changes for using my own components (such as HomeComponent) at @Yurzui and @Linksonder 's solutions. 我在@Yurzui和@Linksonder的解决方案中使用我自己的组件 (例如HomeComponent)做了很小的改动 https://plnkr.co/edit/27x0eg?p=preview https://plnkr.co/edit/27x0eg?p=preview

It's basically adding AppModule to DynamicHtmlModule as additional import inside of createComponentFactory(). 它基本上将AppModule添加到DynamicHtmlModule作为createComponentFactory()内部的附加导入。

@NgModule({ imports: [AppModule, CommonModule, RouterModule, SharedModule], declarations: [decoratedCmp] })
class DynamicHtmlModule { }

And exports our own components at AppModule 并在AppModule上导出我们自己的组件

@NgModule({
  ...
  exports: [HomeComponent, AboutComponent],
  ...
})
export class AppModule { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM