ブラウザの更新やウィンドウのクローズなどに対する保護もカバーするために(問題の詳細については、ギュンターの回答に対する@ChristopheVidalのコメントを参照)、イベントをリッスンするために@HostListenerクラスのcanDeactivate実装にデコレータを追加すると便利beforeunload windowです。正しく構成されている場合、これにより、アプリ内ナビゲーションと外部ナビゲーションの両方が同時に防止されます。
例えば:
成分:
import { ComponentCanDeactivate } from './pending-changes.guard';
import { HostListener } from '@angular/core';
import { Observable } from 'rxjs/Observable';
export class MyComponent implements ComponentCanDeactivate {
  // @HostListener allows us to also guard against browser refresh, close, etc.
  @HostListener('window:beforeunload')
  canDeactivate(): Observable<boolean> | boolean {
    // insert logic to check if there are pending changes here;
    // returning true will navigate without confirmation
    // returning false will show a confirm dialog before navigating away
  }
}
ガード:
import { CanDeactivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
export interface ComponentCanDeactivate {
  canDeactivate: () => boolean | Observable<boolean>;
}
@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    // if there are no pending changes, just allow deactivation; else confirm first
    return component.canDeactivate() ?
      true :
      // NOTE: this warning message will only be shown when navigating elsewhere within your angular app;
      // when navigating away from your angular app, the browser will show a generic warning message
      // see http://stackoverflow.com/a/42207299/7307355
      confirm('WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes.');
  }
}
ルート:
import { PendingChangesGuard } from './pending-changes.guard';
import { MyComponent } from './my.component';
import { Routes } from '@angular/router';
export const MY_ROUTES: Routes = [
  { path: '', component: MyComponent, canDeactivate: [PendingChangesGuard] },
];
モジュール:
import { PendingChangesGuard } from './pending-changes.guard';
import { NgModule } from '@angular/core';
@NgModule({
  // ...
  providers: [PendingChangesGuard],
  // ...
})
export class AppModule {}
注:@JasperRisseeuwが指摘したように、IEとEdge beforeunloadは他のブラウザーとは異なる方法でイベントを処理しfalse、beforeunloadイベントがアクティブになったときに確認ダイアログに単語を含めます(たとえば、ブラウザーの更新、ウィンドウのクローズなど)。Angularアプリ内を移動しても影響はなく、指定した確認警告メッセージが適切に表示されます。IE / Edgeをサポートする必要がありfalse、beforeunloadイベントがアクティブになったときに確認ダイアログに詳細なメッセージを表示したくない場合は、回避策として@JasperRisseeuwの回答を確認することもできます。