有没有办法让对话框自行打开?

Is there a way for a dialog to open itself?

我在一条路线上有一个 angular material 设计对话框组件,我想在导航到该路线时打开该对话框。

有没有办法让 mdDialog 自行打开而不是将其指向 class?

根据 angular material 文档,您可以这样操作对话框组件:

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

根据您的需求,有几个用例:

  1. 在特定的路线/组件上打开它:只需在ngAfterViewInit() { }事件中调用openDialog()方法即可。

  2. 在任何导航事件后打开它:在顶级组件(例如 AppComponent)上使用 angular 路由器并监听事件(示例:

您可以使对话框组件可以通过路由进行导航,并且它可以自行打开。

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