问题描述
我尝试了许多 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
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=preview
来自不同帖子的通用 HTML 出口(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 中使用组件渲染动态模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!