Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 router and modal dialog

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?

like image 409
Sergiy Avatar asked Jun 16 '17 18:06

Sergiy


2 Answers

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

])

like image 86
John Crowson Avatar answered Sep 25 '22 06:09

John Crowson


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

like image 40
birwin Avatar answered Sep 24 '22 06:09

birwin