Popup Modal Dialog from Route Guard
You cannot do this with ngx-bootstrap but you can with @ng-bootstrap/ng-bootstrap.
Example usage from a Service
this.dialogService.show("Logged Out","You are out of here");
Example usage from a route guard
async canActivate() {
if (!this.auth.loggedIn()) {
await this.loginDialogService.confirm();
return this.auth.loggedIn();
}
return true;
}
Source code for the service.
dialog.component.ts
import { Injectable } from '@angular/core';
import {Component} from '@angular/core';
import {NgbModal, ModalDismissReasons,NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-dialog',
templateUrl: './dialog.component.html',
styleUrls: ['./dialog.component.css']
})
export class DialogComponent {
constructor(private modalService: NgbModal,public activeModal: NgbActiveModal) {}
public title: string;
public message: string;
}
@Injectable()
export class DialogService {
constructor(private modalService: NgbModal) {}
public show(title: string, message:string) {
const modalRef = this.modalService.open(DialogComponent);
modalRef.componentInstance.title = title;
modalRef.componentInstance.message = message;
return modalRef.result;
}
}
dialog.component.html
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">{{title}}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" (click)="activeModal.close()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{{message}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" (click)="activeModal.close()">Ok</button>
</div>
You also need to make it an entryComponent
add
entryComponents: [DialogComponent,LoginDialogComponent]
to you @NgModule
Credit to long2know good blog to start with.
Steve Drake
Updated on June 04, 2022Comments
-
Steve Drake almost 2 years
From blog post protecting routes using guards in angular we can pop a message when a user cannot access a route. :
import { CanDeactivate } from '@angular/router'; import { CanDeactivateComponent } from './app/can-deactivate'; export class ConfirmDeactivateGuard implements CanDeactivate<CanDeactivateComponent> { canDeactivate(target: CanDeactivateComponent) { if(target.hasChanges()){ return window.confirm('Do you really want to cancel?'); } return true; } }
I would like to show a modal dialog using ngx-bootstrap to allow the user to login.
I have managed to get some simple code loading the modal from the main app (eg not a child view from my
app.component.ts
), such asshowloginModal() { this.loginModal.show(); }
the modal is loaded from another HTML file with (I include the core login code with the selector app-login
<div class="modal-body"> <app-login #loginModal> </app-login> </div>
edit I have just had a look at Angular2 DialogService – Exploring Bootstrap and that looks like it does the job but it's for bootstrap4