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


我尝试过很多像stackoverflow的选项 动态加载现有组件Angular 2 Final Release

我想要做的是获取一个带有ajax请求的html页面,并在我的自定义组件中渲染/编译此模板。

我已经发现angular2有两个已弃用的组件,我必须使用它 ComponentFactoryResolver

在我的旧解决方案中,我可以设置'[innerHtml]'来呈现HTML。 现在我需要一个新的解决方案。

谁能帮助我?

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>
-->

10364
2017-10-17 17:48


起源

[innerHTML] 从未创建组件。 stackoverflow.com/questions/40060498/... 可能会做你想要的。你怎么看 ComponentFactoryResolver 已弃用? - Günter Zöchbauer
嗨Gunter,我已经尝试过这个解决方案,但它只适用于真正的角度组件而不是自定义组件。我已经从你的帖子编辑了plunkr来重新创建我的问题。 plnkr.co/edit/UACDPBRWNmvjVVsr0dWC - Linksonder
它适用于自定义组件 plnkr.co/edit/TAbupH4si62x10QZ7xuc?p=preview - yurzui
我眨眼之间看不出你和我的片段相比你做了什么不同。是因为你的组件在第二个模块里面吗? - Linksonder
Aaah现在我看到我做错了什么。我没有将“自定义组件”导入动态模块。谢谢你帮我Yurzui! - Linksonder


答案:


问题 解决了 感谢Yurzui,

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

来自不同帖子的通用HTML outlete(Angular 2.1.0动态创建子组件)可用于渲染带有自定义指令的模板。

别忘了导入一个  包含您要渲染的所有自定义组件!

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);
  });
}

8
2017-10-17 18:46





我做了 使用我自己的组件的微小变化 (例如HomeComponent)@Yurzui和@Linksonder的解决方案。 https://plnkr.co/edit/27x0eg?p=preview

它基本上将AppModule添加到DynamicHtmlModule作为createComponentFactory()内部的附加导入。

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

并在AppModule上导出我们自己的组件

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

1
2017-11-10 07:51