Angular 4 router and modal dialog

19,076

Solution 1

My best guess is you may want to subscribe to the activated route and change params in the route to trigger the modal.

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

I believe you would then have a link that looked something like this: <a [routerLink]="['/yourroute', {modal: 'true'}]">

Better examples might be found here: Route Blog

Solution 2

You could also do it using a path instead the above answer which uses a query parameter. Both options are discussed in detail here:

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

TL;DR:

Create a dummy component that just opens the modal on creation:

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

Then add the dummy component to your route:

RouterModule.forRoot([
{
  path: 'home',
  component: BackgroundComponentForModal,
  children: [
    {
      path: 'dialog',
      component: LoginEntryComponent
    }
  ]
},
{ path: '**', redirectTo: 'home' }

])

Share:
19,076

Related videos on Youtube

Sergiy
Author by

Sergiy

Updated on June 04, 2022

Comments

  • Sergiy
    Sergiy almost 2 years

    I have Angular 4 SPA application using Angular router. I want to have hyperlink that opens a component in new dialog using Bootstrap 4. I already know how to open modal dialog from a function.

    But how to open it using hyperlink?

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

    I want to leave my current component in and just show modal dialog in front of it.

    Another question - is it possible to do that programatically? So that I can

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

    and login modal dialog is displayed over current component?

    Any suggestions?

  • Sergiy
    Sergiy almost 7 years
    Thank you for suggestion. What component will be mapped to "/yourroute"? Will it be Cmpl?
  • birwin
    birwin almost 7 years
    It sounds like you really want to just change the route parameters instead of the route itself... I have not done that before, but you could look at this link