angular - 如何以 Angular react 形式保持值(value)?

标签 angular angular6

当用户导航到隐私政策等不同组件并返回表单时,我想在 Angular 表单输入字段中保留值。当用户从隐私政策返回表单时,他应该看到之前输入的数据

最佳答案

  • 如何在点击保存按钮后保存数据。

当用户点击保存按钮时,让我们调用下面的方法,它会删除旧 key 并将新表单 (MessageForm) 数据保存在本地存储中。


      onSave() {
    
        //removes the data with key as user
        localStorage.removeItem("teja");
    
        //adds new data with key as user
        localStorage.setItem("teja", JSON.stringify(this.MessageForm.value));
    
        //reset form once form is edited dirty flag is set 
        //so we need to reset form else on close we get 
        //notification saying form is dirty even when user clicked on save
        this.MessageForm.reset(JSON.parse(localStorage.getItem('teja')));
      }

当我们再次加载页面时,我们可以使用键“teja”从这个存储中检索数据


      ngOnInit(): void {
        //retrieves data if exists.
        if (localStorage.getItem('teja')) {
          this.MessageForm.setValue(JSON.parse(localStorage.getItem('teja')));
        }
      }

  • 用户在未保存的情况下修改了表单并尝试关闭窗口,您有 2 个选择,要么弹出一个窗口说他有未保存的数据,要么将表单存储在本地存储中。我要在这里混合它们。

      @HostListener('window:beforeunload', ['$event']) unloadNotification($event: any) {
        if (this.MessageForm.dirty) {
          //store data
          localStorage.setItem("teja", JSON.stringify(this.MessageForm.value));
          //show popup
          $event.returnValue = true;
        }
      }

使用 Hostistener,您可以处理窗口关闭或页面刷新等事件。在其中,我们检查表单是否脏,只有在用户修改表单时才会设置。 您将看到的一个问题是,如果用户单击保存并尝试关闭窗口,您仍然会看到弹出窗口,提示用户有未保存的数据。那是因为一旦表单被编辑,它的脏标志就会被设置。你需要重置它。 最后在Onsave中添加如下逻辑


    //reset form once form is edited dirty flag is set 
    //so we need to reset form else on close we get 
    //notification saying form is dirty even when user clicked on save
    this.MessageForm.reset(JSON.parse(localStorage.getItem('teja')));

  • 谈到当用户导航到另一个页面而不保存数据时如何保存数据的问题。两种选择
  1. 当用户导航到不同的页面时提供弹出窗口或保存数据 到 localstorage 创建一个如下所示的守卫(命令:ng g guard guard 姓名)

    import { AppComponent } from './../app/app.component';
    import { Injectable } from '@angular/core';
    import { CanActivate, CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
    import { Observable } from 'rxjs';
    
    @Injectable({
      providedIn: 'root'
    })
    export class UnsavedataGuard implements CanDeactivate<unknown> {
    
      canDeactivate(
        component: AppComponent): boolean {
        if (component.MessageForm.dirty) {
          localStorage.setItem("teja", JSON.stringify(component.MessageForm.value));
          return confirm('Are you sure you want to continue? Any unsaved changes will be lost');
        }
        return true;
      }
    
    }

更新您的路线以访问守卫


    const routes: Routes = [
        { path: '', component: AppComponent, canDeactivate: [UnsavedataGuard] },
        { path: '**', component: AppComponent, pathMatch: 'full' }
    ];

  1. 在用户修改表单时将数据保存到本地存储——我将离开这部分的研究,因为代码对我来说不方便 😉

请查找精简教程:https://tejaxspace.com/storage-local-session/

请找到一个 Angular 演示应用程序:https://github.com/tejaswipandava/AngularDataPersistence.git

关于angular - 如何以 Angular react 形式保持值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56899465/

相关文章:

javascript - 如何在 Angular 2 中显示验证错误消息

javascript - 为什么以及如何使用 Angular2/Typescript 模型?

javascript - 我如何在 if 条件下使用 Angular focusout

Angular 2 : Subscribe valuechanges in formbuilder

php - Angular 6/PHP 解析期间 Http 失败

angular6 - 非法状态 : Could not load the summary for directive AppComponent

Angular Observable 不实时显示值

Angular 6 默认路由未加载。我怎样才能解决这个问题?

javascript - 按钮元素在手机上看起来很小