CurlyFro
CurlyFro

Reputation: 1882

Is there a way for a dialog to open itself?

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?

Upvotes: 0

Views: 2873

Answers (2)

Julia Passynkova
Julia Passynkova

Reputation: 17859

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

Upvotes: 3

Alex Beugnet
Alex Beugnet

Reputation: 4071

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)

Upvotes: 1

Related Questions