我尝试过很多像#1_这样的 stackoverflow 选项。
我想要做的是在我的自定义组件中获取带有 ajax 请求的 html 页面和 render/compile 此模板。
我已经发现 angular2 有两个不赞成使用的组件,我必须使用ComponentFactoryResolver。
在我的旧解决方案中,我可以设置'[3]'来呈现 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>
-->
2 回答
问题解决了感谢 Yurzui,
https://plnkr.co/edit/TAbupH4si62x10QZ7xuc?p=preview
来自不同帖子(Angular 2.1.0 动态创建子组件)的通用 HTML outlete 可用于呈现具有自定义指令的模板。
不要忘记使用要渲染的所有自定义组件导入模块!
我在@ @Yurzui and @Linksonder 的解决方案中使用我自己的组件**(例如 HomeComponent)进行了微小的更改。 https://plnkr.co/edit/27x0eg?p=preview
它基本上将 AppModule 添加到 DynamicHtmlModule 作为 createComponentFactory()内的附加导入。
并在 AppModule 上导出我们自己的组件