本文介绍了如何使用angular限制基于页面上呈现的表单组件是否有效的浏览器刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个通用服务,如果刷新时页面上存在任何无效的表单,它将限制用户刷新页面.也就是说,如果表单有效,则允许用户刷新页面,否则不允许(或让用户了解数据丢失情况).

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).

我尝试在服务中注册window.onbeforeload事件,但是没有有关表单组件的信息.

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

推荐答案

我想您可能想研究一下Reactive Forms和诸如Cookies之类的东西.但是使用Cookie,您可以浏览和返回.如果表单有效,则保存到Cookie.

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

app-module.ts

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

...
@NgModule({

imports: [
ReactiveFormsModule
]
})

my-component.html

my-component.html

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

my-component.ts

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

}

这篇关于如何使用angular限制基于页面上呈现的表单组件是否有效的浏览器刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 00:43