首页 > 解决方案 > 在离开页面或更改 Angular 组件中的参数之前保存数据

问题描述

给出以下路径:

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

如何确保每次调用一个自定义方法applyChanges()Section1ComponentSection2Component

  1. 用户离开页面
  2. :idurl参数改变
  3. 作为一个额外的问题,当用户关闭浏览器时?

我目前在中加载资源模型ItemOutletComponent,我在每个部分组件上创建 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 更改应用回模型。页面上没有保存按钮。

标签: angulartypescriptangular-routingangular-reactive-formsangular-forms

解决方案


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

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

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

我们如何检测用户何时关闭浏览器?

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


推荐阅读