0

I am trying to build a generic service which will restrict user from refreshing page if there are any invalid form present on the page at the time of refresh. i.e allow user to refresh page if form is valid else don't allow(or intimate user about data loss).

I tried registering to window.onbeforeload event in my service but don't have information regarding form component .

Deathcr47
  • 53
  • 4

1 Answers1

0

I think you may want to look into Reactive Forms, and something like Cookies perhaps.. If a user can have cookies disabled and scupper that though. But with cookies you can navigate away and back. Saving to cookie if form is valid.

Here's a roadmap to get you started:

npm install cookies-js

app-module.ts

import {ReactiveFormsModule} from '@angular/forms';

...
@NgModule({

imports: [
ReactiveFormsModule
]
})

my-component.html

 <form [formGroup]="form">
    <input name="a" formControlName="xxx">
  </form>

my-component.ts

import {Component,OnInit} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms"
import * as Cookies from 'cookies-js';

export class MyComponent implements OnInit {

  form : FormGroup;
  private static readonly COOKIE_STORE = 'my-component-cookie';


  constructor(private fb: FormBuilder) {
     this.form = this.fb.group({
        xxx:['' Validators.required]
     });

  }

  ngOnInit() {
    const formData = Cookies.get(MyComponent.COOKIE_STORE);
    if (formData) {
      this.form.setValue(
        JSON.parse(formData)
       );
    }
    this.form.valueChanges
      .filter(() => this.form.valid)
      .do(validFormData => 
          Cookies.set(MyComponent.COOKIE_STORE, 
             JSON.stringify(validFormData) 
           )
      )
      .subscribe();
  }

}
JGFMK
  • 8,425
  • 4
  • 58
  • 92