我一直在試圖動態創建一個組件並將其附加到文檔標籤。我一直很難弄清楚如何選擇主體的ViewContainterRef,所以我可以使用ComponentFactoryResolver追加一個新組件。Angular2 - 如何動態創建組件並追加到body的viewcontainer
我試圖使用下面的代碼獲取對身體容器的引用,但它不起作用。有人知道該怎麼做嗎?謝謝!
import {
Component,
ComponentRef,
ApplicationRef,
Injector,
Input,
ViewContainerRef,
ComponentFactoryResolver,
ViewChild,
OnInit,
OnDestroy
} from '@angular/core';
import {
ModalComponent
} from './modal.component';
@Component({
selector: 'my-modal'
})
export class MyModalComponent {
private _bodyRef: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver, private app: ApplicationRef) {
// Does not work!
this._bodyRef = app['_rootComponents'][0]['_hostElement'].vcRef;
}
ngOnInit() {
// Calls the factory to crate a brand new instance
let componentFactory = this.resolver.resolveComponentFactory(ModalComponent);
this._bodyRef.createComponent(componentFactory);
}
}
你可以在我的例子來看看類似的t興googlemap infoWindow http://stackoverflow.com/questions/40922224/angular2-component-into-dynamicaly-created-element/40926110#40926110 – yurzui