Lin*_*der 11 components compilation dynamic angular
我已经尝试了很多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?
}
}
Run Code Online (Sandbox Code Playgroud)
<div #dynamicChild></div>
<!-- Old implementation!
<div *ngIf="!showSource" [innerHTML]="page">
</div>
-->
Run Code Online (Sandbox Code Playgroud)
问题解决了感谢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);
});
}
Run Code Online (Sandbox Code Playgroud)