Jak*_*rth 14 angular-material2 angular
任何人都可以举例说明如何将组件动态加载到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>
Run Code Online (Sandbox Code Playgroud)
yur*_*zui 25
有不同的选择:
1)内置结构指令ngComponentOutlet
<ng-container *ngComponentOutlet="data.component"></ng-container>
Run Code Online (Sandbox Code Playgroud)
2)使用角度材料cdk.更确切地说,您可以PortalModule
从二级入口点使用@angular/cdk/portal
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);
}
Run Code Online (Sandbox Code Playgroud)
dialog.component.html
<ng-template [cdkPortalOutlet]="portal"></ng-template>
Run Code Online (Sandbox Code Playgroud)
3)使用Angular低级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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
dialog.component.html
<ng-template #target></ng-template
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10153 次 |
最近记录: |