我需要从服务中管理对话框组件,因此每个功能的组件都可以调用服务在对话框中打开一个屏幕,所以在我的对话框组件下面显示一个PrimeNG对话框:
@Component({
selector: 'app-dialog',
templateUrl: './dialog.component.html',
styleUrls: ['./dialog.component.css']
})
export class DialogComponent {
display = true;
title = '';
private componentRef;
@ViewChild('content', { read: ViewContainerRef }) contentRef: ViewContainerRef;
constructor() { }
open(component, componentRef) {
this.componentRef = componentRef;
this.contentRef.createComponent(component);
}
onHide(){
this.componentRef.destroy();
}
}
及其模板:
<p-dialog modal="true" [header]="title" [(visible)]="display" (onHide)="onHide()">
<ng-template #content></ng-template>
</p-dialog>
在我的服务之下:
@Injectable()
export class DialogService {
rootViewContainer;
constructor(private factoryResolver: ComponentFactoryResolver) { }
setRootViewContainerRef(viewContainerRef) {
this.rootViewContainer = viewContainerRef
}
public open(component) {
let dialogFactory = this.factoryResolver.resolveComponentFactory(DialogComponent);
let dialogRef = this.rootViewContainer.createComponent(dialogFactory);
let componentFactory = this.factoryResolver.resolveComponentFactory(component);
dialogRef.instance.open(componentFactory, dialogRef);
}
}
我可以使用任何组件的容器引用(“ViewContainerRef”)调用服务的“setRootViewContainerRef”,我需要获取body容器的引用,这样我的所有对话框都将插入到正文中。如何获取body元素的引用?
谢谢
答案 0 :(得分:0)
See the detail how to add component dynamically on page
addComponent(){
// check and resolve the component
var comp = this._cfr.resolveComponentFactory(ExpComponent);
// Create component inside container
var expComponent = this.container.createComponent(comp);
// see explanations
expComponent.instance._ref = expComponent;
}