【问题标题】:Angular 4 router and modal dialogAngular 4 路由器和模态对话框
【发布时间】:2017-11-19 14:46:03
【问题描述】:

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

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

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

我想保留我当前的组件,只在它前面显示模态对话框。

另一个问题 - 是否有可能以编程方式做到这一点?这样我就可以了

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

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

有什么建议吗?

【问题讨论】:

    标签: angular typescript angular4-router


    【解决方案1】:

    我最好的猜测是您可能想要订阅激活的路由并更改路由中的参数以触发模式。

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

    我相信你会有一个看起来像这样的链接: &lt;a [routerLink]="['/yourroute', {modal: 'true'}]"&gt;

    可以在此处找到更好的示例:Route Blog

    【讨论】:

    • 感谢您的建议。什么组件将被映射到“/yourroute”?会是 Cmpl 吗?
    • 听起来您真的只想更改路由参数而不是路由本身...我以前没有这样做过,但是您可以看看这个link
    【解决方案2】:

    您也可以使用路径代替上述使用查询参数的答案。这两个选项都在这里详细讨论:

    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' }
    

    ])

    【讨论】:

      猜你喜欢
      • 2016-04-03
      • 1970-01-01
      • 2014-10-19
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      相关资源
      最近更新 更多