弑天下
这是一种简单的方法,它不依赖于jQuery或Angular 2以外的任何其他库。下面的组件(errorMessage.ts)可以用作任何其他组件的子视图。它只是始终打开或显示的引导程序模式。它的可见性由ngIf语句控制。errorMessage.tsimport { Component } from '@angular/core';@Component({ selector: 'app-error-message', templateUrl: './app/common/errorMessage.html',})export class ErrorMessage{ private ErrorMsg: string; public ErrorMessageIsVisible: boolean; showErrorMessage(msg: string) { this.ErrorMsg = msg; this.ErrorMessageIsVisible = true; } hideErrorMsg() { this.ErrorMessageIsVisible = false; }}errorMessage.html<div *ngIf="ErrorMessageIsVisible" class="modal fade show in danger" id="myModal" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Error</h4> </div> <div class="modal-body"> <p>{{ErrorMsg}}</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" (click)="hideErrorMsg()">Close</button> </div> </div> </div></div>这是父控件的示例(为简洁起见,省略了一些无关的代码):父母import { Component, ViewChild } from '@angular/core';import { NgForm } from '@angular/common';import {Router, RouteSegment, OnActivate, ROUTER_DIRECTIVES } from '@angular/router';import { OnInit } from '@angular/core';import { Observable } from 'rxjs/Observable';@Component({ selector: 'app-application-detail', templateUrl: './app/permissions/applicationDetail.html', directives: [ROUTER_DIRECTIVES, ErrorMessage] // Note ErrorMessage is a directive})export class ApplicationDetail implements OnActivate{ @ViewChild(ErrorMessage) errorMsg: ErrorMessage; // ErrorMessage is a ViewChild // yada yada onSubmit() { let result = this.permissionsService.SaveApplication(this.Application).subscribe(x => { x.Error = true; x.Message = "This is a dummy error message"; if (x.Error) { this.errorMsg.showErrorMessage(x.Message); } else { this.router.navigate(['/applicationsIndex']); } }); }}parent.html<app-error-message></app-error-message>// your html...