Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

359
Visualizações
Dynamically load a component inside a Material MatDialog

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

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.

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.

A simple example:

    <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>
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

There are different options:

1) Built-in structural directive ngComponentOutlet

<ng-container *ngComponentOutlet="data.component"></ng-container> 

Example

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) 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

over 4 years ago · Santiago Trujillo Relatório

0

The actual modal component .ts: (note that the modal component's html is where you will write your code above)

import {Component, Inject, OnInit} from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';


@Component({
    selector: 'app-modal',
    templateUrl: './modal.component.html',
    styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {

    constructor(public dialogRef: MatDialogRef<CreateFirmComponent>,
                @Inject(MAT_DIALOG_DATA) public data: any)
                 {
    }

    ngOnInit() {
    }

    onConfirm() {
        this.dialogRef.close(true);
    }

    onCancel(): void {
        this.dialogRef.close(false);
    }

}

And the component from where you call the Modal:

import {Component, OnInit} from '@angular/core';
import {MatDialog} from '@angular/material';
import {ModalComponent} from './modal-component';


@Component({
    selector: 'app-list',
    templateUrl: './list.component.html',
    styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {


    constructor(public dialog: MatDialog) {
    }




    openDialog(): void {
        let dialogRef = this.dialog.open(ModalComponent, {
            width: '500px'
        });

        dialogRef.afterClosed().subscribe(result => {
            // result is what you get after you close the Modal
        });
    }

}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda