【问题标题】:Add routing to MdDialog for Angular2为 Angular2 添加路由到 MdDialog
【发布时间】:2017-06-14 00:20:58
【问题描述】:

我需要向 MdDialog 组件添加路由,但我不确定解决此问题的最佳方法是什么。

目前,在 foo 页面 (www.app.com/foo/1) 上,用户可以单击一个按钮,它将打开一个 MdDialog 组件 bar。

我想要做的是,在打开 MdDialog 时,它会将/bar/:id 附加到组件中。因此,例如,它将类似于www.app.com/foo/1/bar/1。目标是让用户拥有一个可共享的链接,该链接可以指向 foo,然后打开 MdDialog。

到目前为止,这就是我的应用程序的结构。

app/
  app.component.html <- <router-outlet> is found here
  app.component.ts
  app.module.ts

  foo/
    foo-routing.module.ts
    foo.component.html
    foo.component.ts
    foo.module.ts

    bar/
      bar.component.html <- This bar component file for the MdDialog
      bar.component.ts

  baz/ <- Another section of the website with it's own routing
    baz-routing.module.ts
    baz.component.html
    baz.component.ts
    baz.module.ts
    ...

目前在我的foo-routing.module.ts,我有这个:

const routes: Routes = [
  {
    path: 'foo/:fooId',
    component: FooComponent,
    children: [
      {
        path: 'bar/:barId',
        component: BarDialogComponent
      }
    ]
  }
];

但是,这不起作用。所做的只是打开模块,重新路由到/,并且不允许我点击其他链接。

有人有什么建议或想法吗?谢谢!

【问题讨论】:

  • 你的组件中的路由器插座在哪里?
  • @SurajKhanal 我的主应用程序外壳中有&lt;router-outlet&gt;&lt;/router-outlet&gt;。我已经简化了上面的代码,但是我的应用程序有多个我使用的路由器模块。我主要需要对话框的 URL,以便用户可以轻松地与其他用户共享信息。
  • 将 添加到您的 FooComponent(父路由组件),以便所有子路由都呈现到该组件
  • 嘿@SurajKhanal,我修改了我的原始帖子以更清晰。我的主要父组件中已经有&lt;router-outlet&gt;。问题是 bar 组件位于 MdDialog 内部,并且覆盖在 foo 组件上。

标签: angular material-design angular-material2 angular-router


【解决方案1】:

一个简单的实现方法如下

bar.component.ts

constructor(
  public dialog: MatDialog, 
  @Inject(DOCUMENT) private doc: any, 
  private router: Router) {
  dialog.afterOpen.subscribe(() => {
    if (!doc.body.classList.contains('no-scroll')) {
      doc.body.classList.add('no-scroll');
    }
  });

  this.openModal();
}

openModal() {
  this.dialogRef = this.dialog.open(JazzDialog, this.config);

    this.dialogRef.afterClosed().subscribe((result: string) => {
    this.dialogRef = null;
    this.router.navigate(['../']);
    this.doc.body.classList.remove('no-scroll');
  });
}

Plunker Example

【讨论】:

  • 谢谢@yurzui,这正是我想要的正是。我在玩你的 plunk 并注意到 foo 模块的状态在关闭栏对话框后仍然存在。这是我正在寻找的行为,但我很惊讶地看到 navigate 没有导致 foo 的“新鲜”页面。你知道为什么会这样吗?谢谢!
  • 您的 plunker 似乎无法正常工作。我正在尝试做同样的事情。我想在 url 上加载一个对话框,然后在它关闭时导航到父状态。我所能做的就是回到根状态。
  • afterOpen 无滚动条有什么作用?为什么需要它?
  • @Silthus,显示对话框时通常不需要正文上的滚动条。
猜你喜欢
  • 2021-06-12
  • 2016-01-18
  • 2017-04-01
  • 2017-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
相关资源
最近更新 更多