0

given following paths:

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

how to ensure that a custom method called applyChanges() on Section1Component, resp Section2Component each time:

  1. user navigates away from the page
  2. the :id url parameter changes
  3. as a bonus question, also when user closes the browser?

I currently load resource model in ItemOutletComponent, I create FormGroup on each section component:

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);
}

All I need is to ensure that formGroup changes are applied back to model at appropriate time. There is no Save button on the page.

Liero
  • 25,216
  • 29
  • 151
  • 297

1 Answers1

0

You can use navigation events to detect that user is about to navigate to different location (or not) and do required actions

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

Bonus answer: You will have to use native JS events like windiw:unload and window:beforeunload

How can we detect when user closes browser?

But in it will not work in some cases (eg. killing browser), but that is totally browser dependent

Antoniossss
  • 31,590
  • 6
  • 57
  • 99