[問題] @HostListener('window:beforeunload') 在IE11如何運作?

Use Case: 使用者要更改表單資料,例如使用者要編輯自己的聯絡資料,但按下編輯(Angular Component)以後, 並沒有進行任何編輯(此時save的按鈕應該要是disabled== true的狀態 !form.dirty) 然後使用者可以去點選其他的Component(因為是routing所以windows 理論上應該不會unload)

實際上發生的是,在chrome, edge 都可以work,但是在IE11就會變成,即使使用者沒有編輯任何資料,似乎還是form.dirty == true; save按鈕也是沒有被disabled.
我們的做法是宣告 ComponentCanDeactivate的Interface 接著 PendingChangesGuard 實作ComponentCanDeactivate

可能有用的連結

我個人猜測是因為IE 11 沒有執行@HostListener(‘window:beforeunload’) ? 還是因為我們這樣實作有什麼問題?

 export interface ComponentCanDeactivate {
  canDeactivate: () => boolean;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  static confirmMsg = 'Are you sure you want to leave?';

  canDeactivate(
    component: ComponentCanDeactivate,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {

    if (component.canDeactivate() ) {
      return true;
    }

    const confirmResult = confirm(PendingChangesGuard.confirmMsg);
    return confirmResult;
  }

}

  @ViewChild('form') form: NgForm;
  submitting = false;

  @HostListener('window:beforeunload')
  canDeactivate(): boolean {
    return !this.form.dirty || this.form.submitted;
  }

以下是html

  <div>
      <button mat-raised-button type="submit" color="primary" [disabled]="form.invalid || !form.dirty">{{ 'save' | translate }}</button>
  </div>

沒遇到妳這個問題,我重新用乾淨的環境模擬你的程式碼,跑起來是正常的

IE 11 有出現任何錯誤訊息嗎 (Console)

沒有,Console都沒出現任何東西
然後我有找到一篇好像有寫到IE處理beforeunload事件的方式與其他瀏覽器不同
https://code.i-harness.com/zh-TW/q/2242097