【问题标题】:Save data before leaving page or changing parameter in Angular component在离开页面或更改 Angular 组件中的参数之前保存数据
【发布时间】:2026-02-04 04:35:01
【问题描述】:

给定以下路径:

const appRoutes: Routes = [
  { path: '', component: ListComponent },
  { path: 'items/:id', component: ItemOutletComponent,
    children:[
      { path: '', component: Section1Component },
      { path: 'page2', component: Section2Component, },
    ]
  }];

如何确保每次在 Section1ComponentSection2Component 上调用一个名为 applyChanges() 的自定义方法:

  1. 用户离开页面
  2. :id url 参数变化
  3. 作为附加问题,当用户关闭浏览器时也是如此?

我目前在ItemOutletComponent加载资源模型,我在每个section组件上创建FormGroup:

ngOnInit() {
  this.formGroup = new FormGroup({
     section1: new FormGroup({
       prop1: new FormControl(),
       prop2: new FormControl()
  });
  this.formGroup.pathValue(this.model);
}

applyChanges() {
  Object.assign(this.model, this.formGroup.value);
}

我只需要确保在适当的时间将 formGroup 更改应用回模型。页面上没有保存按钮。

【问题讨论】:

    标签: angular typescript angular-routing angular-reactive-forms angular-forms


    【解决方案1】:

    您可以使用导航事件来检测用户是否将导航到不同的位置(或不导航)并执行所需的操作

    https://angular.io/guide/router#router-events

    奖励答案: 您将不得不使用原生 JS 事件,例如 windiw:unloadwindow:beforeunload

    How can we detect when user closes browser?

    但在某些情况下它不起作用(例如杀死浏览器),但这完全取决于浏览器

    【讨论】: