angular - 在离开页面或更改 Angular 组件中的参数之前保存数据
问题描述
给出以下路径:
const appRoutes: Routes = [
{ path: '', component: ListComponent },
{ path: 'items/:id', component: ItemOutletComponent,
children:[
{ path: '', component: Section1Component },
{ path: 'page2', component: Section2Component, },
]
}];
如何确保每次调用一个自定义方法applyChanges()
:Section1Component
Section2Component
- 用户离开页面
:id
url参数改变- 作为一个额外的问题,当用户关闭浏览器时?
我目前在中加载资源模型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 更改应用回模型。页面上没有保存按钮。
解决方案
您可以使用导航事件来检测用户将要导航到不同的位置(或不导航到)并执行所需的操作
https://angular.io/guide/router#router-events
奖励答案:您将不得不使用原生 JS 事件,例如windiw:unload
和window:beforeunload
但是在某些情况下它不起作用(例如杀死浏览器),但这完全取决于浏览器
推荐阅读
- git - Git,仅在推送时忽略文件
- ruby-on-rails - Nginx 和 Ruby on Rails - HTTP 301 仅在公共 IP 地址上永久移动
- swiftui - 在初始化之前使用结构
- c# - 当label1.BackColor = ColorTransparent时,整个标签变透明,文字消失
- html - 网页右侧出现不需要的白色竖条
- javascript - 使用 TS 或 JS 在 Angular 应用程序中将带有 GMT 的日期转换为人类可读的时区
- c# - 是否可以在 Win2d 中为笔画添加纹理?
- excel-2010 - 我只需要有人向我展示如何在有限制和无限制的情况下进行所有组合
- java - 错误:-source 8 中不支持记录
- javascript - 在页面加载时扫描某些类元素的值并仅对具有某些值的几个元素运行函数