Angular 4路由器和模态对话框

问题描述 投票:10回答:2

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

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

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

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

另一个问题 - 是否有可能以编程方式执行此操作?这样我就可以

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

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

有什么建议?

angular typescript angular4-router
2个回答
9
投票

我最好的猜测是你可能想要订阅激活的路线并改变路线中的参数以触发模态。

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


0
投票

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

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

])

© www.soinside.com 2019 - 2024. All rights reserved.