Autosave form values in localStorage using template forms or reactive forms in Angular.
npm install ngx-autosave-form --saveimport { NgxAutosaveFormModule, NgxForm } from 'ngx-autosave-form';@Component({
selector: 'app-root',
standalone: true,
imports: [FormsModule, NgxAutosaveFormModule]
})<!-- id: is required -->
<!-- ngxAutosaveForm: boolean, true for autosave -->
<form id="myForm" [ngxAutosaveForm]="true" #form1="ngForm">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" [(ngModel)]="data.name" />
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" name="lastName" [(ngModel)]="data.lastName" />
</div>
</form>@ViewChild('form1') form1!: NgxForm; // Important to use NgxForm
this.form1.save(); // save to localStorage
this.form1.read(); // read from localStorage
this.form1.clear(); // clear localStorageExample:
ngOnInit () {
setTimeout(() => {
const formValue = this.form1.read();
if (formValue) {
this.data = formValue;
}
}, 0);
}Note: Use setTimeout to prevent error "Cannot read properties of undefined (reading 'read')"
import { NgxAutosaveFormModule, NgxFormGroup } from 'ngx-autosave-form';@Component({
selector: 'app-root',
standalone: true,
imports: [ReactiveFormsModule, NgxAutosaveFormModule]
})<!-- id: is required -->
<!-- ngxAutosaveReactiveForm: boolean, true for autosave -->
<form id="myForm" [ngxAutosaveReactiveForm]="true" [formGroup]="form1">
<div class="form-group">
<label>Name</label>
<input type="text" formControlName="name" />
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" formControlName="lastName" />
</div>
</form>form1!: FormGroup;
ngxForm1!: NgxFormGroup;
this.ngxForm1.save(); // save to localStorage
this.ngxForm1.clear(); // clear localStorage
this.ngxForm1.read(); // read from localStorageExample:
ngOnInit () {
this.form1 = new FormGroup({
'name': new FormControl(''),
'lastName': new FormControl(''),
});
this.ngxForm1 = this.form1 as NgxFormGroup; // cast FormGroup to NgxFormGroup
setTimeout(() => {
const formValue = this.ngxForm1.read();
if (formValue) {
this.ngxForm1.setValue(formValue)
}
}, 0);
}