我已經嘗試了很多像flipfloader選項一樣的Load existing components dynamically Angular 2 Final Release。如何在Angular2中使用組件呈現動態模板
我想要做的就是獲取一個帶有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的]'從未創建的組件。 http://stackoverflow.com/questions/40060498/angular-2-1-0-create-child-component-on-the-fly-dynamically/40080290#40080290可能會做你想做的。你認爲什麼[ComponentFactoryResolver](https://angular.io/docs/ts/latest/api/core/index/ComponentFactoryResolver-class.html)已被棄用? –
嗨Gunter,我試過這個解決方案,但它只適用於真正的角度組件而不是定製的。我已經編輯了您發佈的plunkr以重新創建我的問題。 https://plnkr.co/edit/UACDPBRWNmvjVVsr0dWC – Linksonder
它可以與自定義組件一起工作https://plnkr.co/edit/TAbupH4si62x10QZ7xuc?p=preview – yurzui