I encountered an issue with my form component where it displays previous values instead of updated ones during a save operation. The strange part is that if I close the form and reopen it, the new values are then shown correctly. It seems like the problem lies in the fact that the old values stored in 'selectedContact' are being passed into the form as 'contactForm' during the save process, causing the new values to be overwritten by the old ones on the form controls. My data management is handled using NgRx Store.
I'm unsure how to prevent the form from displaying old values when saving. Is there a way to pause the form from updating?
Parent modal component:
@Component({
selector: 'parent-modal',
template: `
<ng-template #childTemplate>
<contact-form
[contactForm]="contactForm"
[loading]="(loading$ | async)!"
(cancel)="close()"
(save)="save($event)"
*ngIf="contactForm"
></contact-form>
<web-modal
[childTemplate]="childTemplate"
[visible]="(isPopupOpen$ | async)!"
(cancel)="close()"
>
</web-modal>
`,
styles: [],
})
export class ContactModalComponent {
@Input() public selectedContact!: Contact | null;
public isPopupOpen$!: Observable<boolean>;
public loading$: Observable<boolean>;
public constructor(
private store: Store<ContactPartialState>,
configurationStore: Store<ConfigurationState>,
) {
this.isPopupOpen$ = store.select(contacttQuery.getIsContactOpen);
this.loading$ = store.select(contactQuery.getLoading);
}
public get contactForm(): Contact {
return this.selectedContact as Contact;
}
public close(): void {
this.store.dispatch(closeContact());
}
public save(form: Contact): void {
this.store.dispatch(saveContact({ payload: form }));
}
}
Child form component:
@Component({
selector: 'contact-form',
templateUrl: '../contact-form/contact-form.component.html',
})
export class ContactFormComponent implements OnChanges {
@Input() public contactForm!: Contact | null;
@Input() public loading: boolean;
@Output() public cancel: EventEmitter<void>;
@Output() public save: EventEmitter<Contact>;
public form!: FormGroup;
public constructor(
fb: FormBuilder,
) {
this.loading = false;
this.cancel = new EventEmitter<void>();
this.save = new EventEmitter<Contact>();
this.contactForm = new Contact();
this.createForm();
}
public ngOnChanges(): void {
this.createForm();
}
public createForm(): void {
// add form controls
}
public emitCancel(): void {
this.cancel.emit();
}
public emitSave(): void {
this.form.markAllAsTouched();
if (this.form.valid) {
const contact = new Contact(this.form.value);
this.save.emit(contact);
}
}
}