web-dev-qa-db-ja.com

Angular 4つのルーターとモーダルダイアログ

Angularルーターを使用するAngular 4 SPAアプリケーションがあります。 Bootstrap 4を使用して、新しいダイアログでコンポーネントを開くハイパーリンクが必要です。4.関数からモーダルダイアログを開く方法を既に知っています。

しかし、ハイパーリンクを使用してそれを開く方法は?

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

現在のコンポーネントをそのままにして、その前にモーダルダイアログを表示したいだけです。

別の質問-それをプログラムで行うことは可能ですか?私ができるように

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

ログインモーダルダイアログは現在のコンポーネント上に表示されますか?

助言がありますか?

10
Sergey

私の最善の推測は、アクティブ化されたルートをサブスクライブし、ルートのパラメーターを変更してモーダルをトリガーすることです。

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

9
birwin

クエリパラメータを使用する上記の回答の代わりにパスを使用して行うこともできます。両方のオプションについて、ここで詳しく説明します。

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

])

0
John Crowson