Opening modal conditionally in Angular material

I'm using Angular Material Dialog to open a modal. In the modal that opens, I have few components that every time a different one should be loaded based on a condition. The thing is, I tried to pass the .open() method the component name as a string, and it gives error.

For example, let's say this the method:

openDialog(): void {
const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
  width: '250px',
});

I tried to do something like:

let myComp: string = 'DialogOverviewExampleDialog'; 

openDialog(): void {
  const dialogRef = this.dialog.open(this.myComp, {
  width: '250px',
});

But it gives error. It just don't get a variable as a parameter to the function.

The reason I need to pass the name as a string, so I can create a condition, assign for each condition the component that should be open in the modal, then just pass the .open() method the variable with the name of the desire component to be load

What's wrong?

Thanks.

2 answers

  • answered 2018-07-11 05:55 Bhanu Tej P

    The DialogOverviewExampleDialog is a class. So modify your code to

    let myComp: any = DialogOverviewExampleDialog; 
    
    openDialog(): void {
      const dialogRef = this.dialog.open(this.myComp, {
      width: '250px',
    });
    

  • answered 2018-07-11 06:19 Fouad Kajj

    Try this:

    let myComp : DialogOverviewExampleDialog