2

从博客文章中,我们可以在用户无法访问路由时弹出一条消息。:

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

我想使用ngx-bootstrap显示一个模式对话框以允许用户登录。

我已经设法从主应用程序(例如不是我的子视图app.component.ts)中加载了一些简单的代码,例如

showloginModal() {
  this.loginModal.show();
}

模态是从另一个 HTML 文件加载的(我在选择器 app-login 中包含了核心登录代码

<div class="modal-body">
  <app-login  #loginModal> </app-login>
</div>

编辑 我刚刚看过Angular2 DialogService – Exploring Bootstrap,看起来它可以完成这项工作,但它适用于 bootstrap4

4

1 回答 1

3

你不能用ngx-bootstrap做到这一点,但你可以用@ng-bootstrap/ng-bootstrap

示例用法Service

this.dialogService.show("Logged Out","You are out of here");

示例用法route guard

async canActivate() {
  if (!this.auth.loggedIn()) {
    await this.loginDialogService.confirm();
    return this.auth.loggedIn();
  }
  return true;
}

服务的源代码。

对话框组件.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">&times;</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>

您还需要将其entryComponent添加到

entryComponents: [DialogComponent,LoginDialogComponent]

给你@NgModule

归功于 long2know好的博客。

于 2017-05-08T15:51:43.400 回答