任何人都可以提供如何动态加载组件到Material MatDialog的示例吗?
我想要做的是:我将为MatDialog配置数据提供一个组件类型,然后该对话框将创建一个实例并放置在它的mat-dialog-content区域内.
看来我需要使用ng-template和viewContainerRef的某种组合,但我不知道如何实例化提供的组件Type并插入到所需的区域.
一个简单的例子:
<h2 mat-dialog-title>MyTitle</h2> <mat-dialog-content> <---- dynamically loaded component would be inserted here ----> </mat-dialog-content> <mat-dialog-actions> <button mat-button mat-dialog-close>Cancel</button> <button mat-button [mat-dialog-close]="true">Save</button> </mat-dialog-actions>
有不同的选择,如:
原文链接:https://www.f2er.com/angularjs/142171.html1)内置结构指令ngComponentOutlet
<ng-container *ngComponentOutlet="data.component"></ng-container>
2)使用角度材料cdk.更准确地说,您可以从辅助入口点@ angular / cdk / portal使用PortalModule
dialog.component.ts
import { ComponentPortal } from '@angular/cdk/portal'; @Component({...}) export class DialogDialog { portal: ComponentPortal<any>; constructor(... @Inject(MAT_DIALOG_DATA) public data: any) { } ngOnInit() { this.portal = new ComponentPortal(this.data.component); }
dialog.component.html
<ng-template [cdkPortalOutlet]="portal"></ng-template>
3)使用角度API
dialog.component.ts
@Component({...}) export class DialogDialog { @ViewChild('target',{ read: ViewContainerRef }) vcRef: ViewContainerRef; componentRef: ComponentRef<any>; constructor( ... private resolver: ComponentFactoryResolver,@Inject(MAT_DIALOG_DATA) public data: any) { } ngOnInit() { const factory = this.resolver.resolveComponentFactory(this.data.component); this.componentRef = this.vcRef.createComponent(factory); } ngOnDestroy() { if (this.componentRef) { this.componentRef.destroy(); } } }
dialog.component.html
<ng-template #target></ng-template