How to restrict browser refresh based on whether rendered form component on a page is valid or not using angular

后端 未结 1 652
日久生厌
日久生厌 2021-01-16 20:52

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

1条回答
  •  粉色の甜心
    2021-01-16 21:43

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

    0 讨论(0)
提交回复
热议问题