【发布时间】:2017-02-26 19:21:07
【问题描述】:
我已经尝试了许多 stackoverflow 选项,例如 Load existing components dynamically 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>
-->
【问题讨论】:
-
[innerHTML]从未创建过组件。 stackoverflow.com/questions/40060498/… 可能会做你想做的事。您认为 ComponentFactoryResolver 已被弃用的是什么? -
您好 Gunter,我已经尝试过这个解决方案,但它只适用于真正的角度组件,而不适用于自定义组件。我已经编辑了您发布的 plunkr 以重新创建我的问题。 plnkr.co/edit/UACDPBRWNmvjVVsr0dWC
-
与我的sn-p相比,我一眨眼就看不出你做了什么。是因为你的组件在第二个模块中吗?
-
啊现在我明白我做错了什么。我没有将我的“自定义组件”导入动态模块。感谢您帮助我解决 Yurzui!
标签: angular dynamic compilation components