在材料MatDialog中动态加载零部件 [英] Dynamically load a component inside a Material MatDialog

查看:156
本文介绍了在材料MatDialog中动态加载零部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以提供一个如何将组件动态加载到Material MatDialog中的示例吗?

Can anyone provide an example of how to dynamically load a component into a Material MatDialog?

我想做的是:我将为MatDialog配置数据提供一个组件类型,然后对话框将为其创建实例并将其放置在其mat-dialog-content区域中.

What I would like to do is this: I will provide the MatDialog configuration data with a component Type which the dialog would then create an instance of and place inside it's mat-dialog-content area.

看来我需要使用ng-template和viewContainerRef的某种组合,但我不知道如何实例化所提供的组件Type并将其插入所需的区域.

It appears I would need to use some combination of ng-template and viewContainerRef, but I do not know how to instantiate the provided component Type and insert into the desired area.

一个简单的例子:

    <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

2) Using angular material cdk. More precisely you can use PortalModule from secondary entry point @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);
  }
      

dialog.component.html

<ng-template [cdkPortalOutlet]="portal"></ng-template>

示例

Example

3)使用Angular低级API

3) Using Angular low-level 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

这篇关于在材料MatDialog中动态加载零部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆