0

i have an angular material design dialog component on a route and i'd like to open the dialog when i navigate to that route.

is there a way for the mdDialog to open itself rather than pointing it to a class?

CurlyFro
  • 1,862
  • 4
  • 22
  • 39
  • 2
    What do you mean by `pointing it to a class` ? – Alex Beugnet Aug 30 '17 at 15:55
  • 1
    Call the dialog `open` method in `ngAfterViewInit()` lifecycle hook – FAISAL Aug 30 '17 at 16:00
  • 1
    Yes, it's possible to open a dialog. You'll still need to construct the dialog in the same way as before, but instead of calling a method on click to use `.open()` you'll direct call it within a `ngAfterViewChecked() { }`. – Z. Bagley Aug 30 '17 at 16:00

2 Answers2

3

You can make dialog component to be navigable via routes and it can open itself.

 @Component({
    selector: 'app-dialog-data',
    template: `<ng-template>dialog-data works!</ng-template>`,
    styleUrls: ['./dialog-data.component.scss']
  })
  export class DialogDataComponent implements AfterViewInit {
    @ViewChild(TemplateRef) ref;

    constructor(private dialog: MdDialog) {}

    ngAfterViewInit() {
      setTimeout(() => {this.dialog.open(this.ref);}, 0);
    }
  }
Julia Passynkova
  • 17,256
  • 6
  • 33
  • 32
1

From the angular material documentation, you manipulate your dialog component this way :

constructor(public dialog: MdDialog) {}

  openDialog(): void {
    let dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
      width: '250px',
      data: { name: this.name, animal: this.animal } // random irrelevant data
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      this.animal = result;                          // random irrelevant data
    });
  }
}

From your needs, there are several use cases :

  1. Open it on a specific route / component : Simply call the openDialog() method in the ngAfterViewInit() { } event.

  2. Open it after any navigation event : Use the angular router on a top level component (such as AppComponent) and listen to the events (example : Show loading screen when navigating between routes in Angular 2)

Alex Beugnet
  • 4,003
  • 4
  • 23
  • 40