Skip to content

Instantly share code, notes, and snippets.

@NetanelBasal
Created May 10, 2020 06:44
Show Gist options
  • Save NetanelBasal/69cdcc341a0edd17ccd2365bd795c44a to your computer and use it in GitHub Desktop.
Save NetanelBasal/69cdcc341a0edd17ccd2365bd795c44a to your computer and use it in GitHub Desktop.
import { Directive, HostListener, Input, OnInit, Self } from '@angular/core';
import { ControlContainer } from '@angular/forms';
import { debounceTime, filter, take } from 'rxjs/operators';
import { fromEvent, merge, Subject } from 'rxjs';
import { StorageService } from './storage.service';
@Directive({
selector: 'form[formGroup][name]'
})
export class FormStorageDirective implements OnInit {
@Input() name: string;
@Input() saveStrategy: 'change' | 'unload' = 'unload';
private destroy = new Subject();
private destroy$ = this.destroy.asObservable();
constructor(@Self() private container: ControlContainer, private storage: StorageService) {
}
@HostListener('submit')
onSubmit() {
this.storage.removeItem(this.key);
}
private get key() {
return `${this.name}-form`;
}
private get group() {
return this.container.control;
}
async ngOnInit() {
this.saveStrategy === 'unload' ? this.unloadStrategy() : this.changeStrategy()
const storageValue = await this.storage.getItem(this.key);
if(storageValue) this.group.patchValue(storageValue);
}
private unloadStrategy() {
merge(
fromEvent(window, 'beforeunload'),
this.destroy$
).pipe(
filter(() => this.group.dirty),
take(1)
).subscribe(() => this.saveValue(this.group.value));
}
private changeStrategy() {
this.group.valueChanges.pipe(debounceTime(400))
.subscribe(value => this.saveValue(value))
}
private saveValue(value) {
this.storage.setItem(this.key, value);
}
ngOnDestroy() {
this.destroy.next();
}
}
@dpapini
Copy link

dpapini commented Mar 1, 2021

good code, but i've question. this work for complex reactive form where exists nested formGroup?
thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment