我希望在用户跳转到其他组件(如隐私政策)然后回到表单时,可以将值保留在 Angular 表单输入字段中。当用户从隐私政策返回表单时,应该看到之前输入的数据。
当用户单击保存按钮时,调用以下方法,它会删除旧键并将新表单(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')));
}
ngOnInit(): void {
//retrieves data if exists.
if (localStorage.getItem('teja')) {
this.MessageForm.setValue(JSON.parse(localStorage.getItem('teja')));
}
}
@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;
}
}
//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')));
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' }
];
请查看压缩教程:https://tejaxspace.com/storage-local-session/
请查看Angular演示应用程序:https://github.com/tejaswipandava/AngularDataPersistence.git
你可以使用
localStorage
。它非常易于使用。
var data = "some data";
localStorage.setItem("data_item", data);
localStorage.getItem("data_item"); //returns "some data"
或者
使用 SessionStorage
或 cookies 来存储您的数据。
当您刷新页面时,将您的数据复制到上述任何一种存储中,并在初始化时将其复制回您的变量中。请参考下面的示例。将 sessionStorage 替换为 localStorage 可以将数据存储在 localStorage 中。
In AppComponent
ngOnInit() {
if (sessionStorage.getItem("user")) {
this.data.changeUser(sessionStorage.getItem("user"));
}
}
@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any) {
sessionStorage.setItem("user", this.getUser());
}
<input FormControl="name" (input)="saveValue"/>
在你的ts文件中:
saveValue() {
this.name = this.form.get('name').value;
}
当你回到表单时,请调用reBuild函数。
reBuild() {
this.form.get('name').setValue(this.name) ;
}