Tôi đã thử nhiều tùy chọn ngăn xếp luồng như Load existing components dynamically Angular 2 Final Release.Cách hiển thị mẫu động có các thành phần trong Angular2
Điều tôi muốn làm là tải trang html có yêu cầu ajax và hiển thị/biên dịch mẫu này trong thành phần tùy chỉnh của tôi.
Tôi đã tìm ra rằng angular2 có hai thành phần không được dùng nữa và tôi phải sử dụng ComponentFactoryResolver.
Trong giải pháp cũ của tôi, tôi chỉ có thể đặt '[innerHtml]' để hiển thị HTML. Bây giờ tôi cần một giải pháp mới.
Ai có thể giúp tôi?
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]' thành phần không bao giờ tạo ra. http://stackoverflow.com/questions/40060498/angular-2-1-0-create-child-component-on-the-fly-dynamically/40080290#40080290 có thể làm những gì bạn muốn. Bạn nghĩ gì về [ComponentFactoryResolver] (https://angular.io/docs/ts/latest/api/core/index/ComponentFactoryResolver-class.html) không được chấp nhận? –
Hi Gunter, tôi đã thử giải pháp này nhưng nó chỉ hoạt động cho các thành phần góc thực và không tùy chỉnh. Tôi đã chỉnh sửa plunkr từ bạn đang đăng bài để tái tạo vấn đề của tôi. https://plnkr.co/edit/UACDPBRWNmvjVVsr0dWC – Linksonder
Nó hoạt động với các thành phần tùy chỉnh https://plnkr.co/edit/TAbupH4si62x10QZ7xuc?p=preview – yurzui