angular – 在Material MatDialog中动态加载组件
发布时间:2020-12-17 07:29:47 所属栏目:安全 来源:网络整理
导读:任何人都可以提供如何动态加载组件到Material MatDialog的示例吗? 我想要做的是:我将为MatDialog配置数据提供一个组件类型,然后该对话框将创建一个实例并放置在它的mat-dialog-content区域内. 看来我需要使用ng-template和viewContainerRef的某种组合,但我
任何人都可以提供如何动态加载组件到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>
有不同的选择,如:
1)内置结构指令ngComponentOutlet <ng-container *ngComponentOutlet="data.component"></ng-container> Example 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> Example 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 Example (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |