【问题标题】:Is there a way for a dialog to open itself?有没有办法让对话框自行打开?
【发布时间】:2018-02-08 10:19:54
【问题描述】:

我在路线上有一个角度材料设计对话框组件,我想在导航到该路线时打开对话框。

有没有办法让 mdDialog 自己打开而不是指向一个类?

【问题讨论】:

  • pointing it to a class 是什么意思?
  • ngAfterViewInit()生命周期钩子中调用对话框open方法
  • 是的,可以打开一个对话框。您仍然需要以与以前相同的方式构建对话框,但不是在单击时调用方法来使用.open(),而是直接在ngAfterViewChecked() { } 中调用它。

标签: angular angular-routing angular-material2


【解决方案1】:

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

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

【讨论】:

  • 我将我的组件添加到 entryComponents 但我仍然收到此错误:'未找到未定义的组件工厂。你把它添加到@NgModule.entryComponents'
  • 下一个问题:如果用户在对话框外点击,我需要导航到某个地方。如果我可以访问 DialogRef,我会使用 afterClosed。有什么简单的方法吗?
  • 知道了。使用 afterAllClosed
  • @CurlyFro 您能解释一下您是如何解决“未找到未定义的组件工厂”错误的吗?我在任何地方都找不到答案
【解决方案2】:

从角度材料文档中,您可以通过这种方式操作对话框组件:

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)上使用角度路由器并监听事件(例如:Show loading screen when navigating between routes in Angular 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    相关资源
    最近更新 更多