Я пытаюсь создать директиву, которая отображает полосу загрузки, когда пользователь печатает, и отправляет ввод, когда пользователь прекратил печатать.
import { Directive, EventEmitter, Input, Output } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { debounceTime, tap } from 'rxjs/operators';
import { Subscription } from 'rxjs';
@Directive({
selector: '[appAutoSave]',
})
export class AutoSaveDirective {
@Input() formGroup!: FormGroup;
private _state!: 'loading' | 'synced' | 'modified' | 'error';
@Output() stateChange = new EventEmitter<string>();
@Output() onSubmit = new EventEmitter();
@Output() formError = new EventEmitter<string>();
private formSub!: Subscription;
ngOnInit() {
this.preloadData();
this.autoSave();
}
preloadData() {
this.formGroup.markAsPristine();
// this.state = 'synced';
}
// Autosaves form changes
autoSave() {
console.log('inside changes');
this.formSub = this.formGroup.valueChanges
.pipe(
tap(change => {
this.state = 'modified';
}),
debounceTime(2000),
tap(change => {
if (this.formGroup.valid && this._state === 'modified') {
// this.onSubmit.emit();
this.state = 'synced';
}
}),
)
.subscribe();
}
set state(val: any) {
this._state = val;
this.stateChange.emit(val);
if (val === 'synced') {
this.onSubmit.emit();
}
}
ngOnDestroy() {
this.formSub.unsubscribe();
}
}
changeState(event: string) {
this.changeHandler.emit(event);
if (event === 'synced') { // condition
this.submit();
}
}
Если я удалю вышеуказанное условие if все работает нормально. Но я должен вызвать функцию submit, когда значения синхронизируются, и пользователь перестал печатать.
<form
[formGroup]="situationFormGroup"
appAutoSave
(stateChange)="changeState($event)"
>