如何使用Angular2中的组件呈现动态模板 [英] How to render a dynamic template with components in Angular2
问题描述
我尝试过许多stackoverflow选项,如加载现有组件动态Angular 2 Final Release 。
I've tried many stackoverflow options like Load existing components dynamically Angular 2 Final Release.
我想做的是获取一个带有ajax请求的html页面,并在我的自定义中渲染/编译此模板零件。
What i want to do is get a html page with a ajax request and render/compile this template in my custom component.
我已经弄清楚,angular2有两个弃用的组件,我必须使用 ComponentFactoryResolver 。
I've figured out that angular2 has two deprecated components and that i have to use ComponentFactoryResolver.
在我的旧解决方案中,我可以设置一个'[innerHtml]'来呈现HTML。
现在我需要一个新的解决方案。
In my old solution i could just set a '[innerHtml]' to render the HTML. Now i need a new solution.
谁可以帮助我?
page.component.ts 从'@ angular / core'导入{Component,ViewChild,ViewContainerRef,ComponentFactory,OnInit,ComponentFactoryResolver}中的
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>
-->
推荐答案
解决问题 Yurzui,
Problem solved Thanks to Yurzui,
https:// plnkr .co / edit / TAbupH4si62x10QZ7xuc?p =预览
从另一个帖子( Angular 2.1.0动态创建子组件,动态)可以用于在其中显示带有自定义指令的模板。
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.
不要忘记使用您要呈现的所有自定义组件导入模块
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);
});
}
这篇关于如何使用Angular2中的组件呈现动态模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!