Angular 4 路由和模态对话框

11

我有一个使用Angular路由器的Angular 4 SPA应用程序。我想要一个超链接,使用Bootstrap 4在新对话框中打开组件。我已经知道如何从函数中打开模态对话框。

但是如何使用超链接打开它呢?

<a [routerLink]="['/login']">Login</a>

我希望能够在当前组件中保留并在其前显示模态对话框。

另一个问题-是否可以通过编程实现这一点?这样我就可以

this.router.navigate(['/login']);

并且登录模态对话框显示在当前组件上?

有任何建议吗?


我认为将模态与路由混合使用不是一个好的编程实践。它可以被实现并不代表这是一个好的实践。 路由应该链接到页面,而不是模态——请考虑SEO(搜索引擎优化)。 - Sebastian Scholle
2个回答

11

我的最佳猜测是您可能希望订阅已激活的路由并更改路由中的参数以触发模态框。

import { ActivatedRoute, Params } from '@angular/router';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'cmp1',
  templateUrl: './cmp1.component.html',
  styleUrls: ['./cmp1.component.css'],
})
export class Cmp1 implements OnInit {

    constructor(private activatedRoute: ActivatedRoute) {
    }

    ngOnInit() {
        this.activatedRoute.params.subscribe(params => {
            if (params["modal"] == 'true') {
                // Launch Modal here
            }
        });
    }
}

我相信你将拥有类似于这样的链接:

<a [routerLink]="['/yourroute', {modal: 'true'}]">

更好的示例可以在这里找到:Route Blog


谢谢您的建议。哪个组件将映射到“/yourroute”?它会是Cmpl吗? - Sergiy
听起来你真的只想改变路由参数而不是路由本身... 我以前没有做过这样的事情,但你可以查看这个链接:https://stackoverflow.com/questions/40283562/how-to-change-only-params-of-route-in-angular2 - birwin

3
你也可以使用路径来实现它,而不是使用查询参数。这两个选项在这里都有详细讨论:

https://medium.com/ngconf/routing-to-angular-material-dialogs-c3fb7231c177

TL;DR:

创建一个虚拟组件,在创建时只需打开模态框:

@Component({
  template: ''
})
export class LoginEntryComponent {
  constructor(public dialog: MatDialog, private router: Router,
    private route: ActivatedRoute) {
    this.openDialog();
  }
  openDialog(): void {
    const dialogRef = this.dialog.open(LoginComponent);
    dialogRef.afterClosed().subscribe(result => {
      this.router.navigate(['../'], { relativeTo: this.route });
    });
  }
}

然后将虚拟组件添加到您的路由中:
RouterModule.forRoot([
{
  path: 'home',
  component: BackgroundComponentForModal,
  children: [
    {
      path: 'dialog',
      component: LoginEntryComponent
    }
  ]
},
{ path: '**', redirectTo: 'home' }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接