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