66 lines
2.3 KiB
TypeScript
66 lines
2.3 KiB
TypeScript
import { Component, EventEmitter, input, Input, Output, signal } from "@angular/core";
|
|
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms";
|
|
import { Error } from "@app/shared/components/error/error";
|
|
import { AddressRequest, AddressResponse } from "@app/features/checkout/services/address-service";
|
|
import { LoadingSpinner } from "@shared/components/loading-spinner/loading-spinner";
|
|
|
|
@Component({
|
|
selector: "app-address-form",
|
|
imports: [ReactiveFormsModule, Error, LoadingSpinner],
|
|
templateUrl: "./address-form.html",
|
|
styleUrl: "./address-form.css",
|
|
})
|
|
export class AddressForm {
|
|
@Output() submitAddress: EventEmitter<AddressRequest> = new EventEmitter<AddressRequest>();
|
|
@Output() updateAddress: EventEmitter<AddressResponse> = new EventEmitter<AddressResponse>();
|
|
@Output() editingCanceled: EventEmitter<void> = new EventEmitter<void>();
|
|
|
|
isProcessing = input<boolean>(false);
|
|
|
|
addressForm = new FormGroup({
|
|
firstName: new FormControl("", {
|
|
validators: [Validators.required, Validators.pattern("^[a-zA-Z]\\S+$")],
|
|
}),
|
|
lastName: new FormControl("", {
|
|
validators: [Validators.required, Validators.pattern("^[a-zA-Z]\\S+$")],
|
|
}),
|
|
street: new FormControl("", { validators: Validators.required }),
|
|
city: new FormControl("", { validators: Validators.required }),
|
|
state: new FormControl("", { validators: Validators.required }),
|
|
pinCode: new FormControl("", {
|
|
validators: [Validators.required, Validators.pattern("^[0-9]{6}$")],
|
|
}),
|
|
});
|
|
protected isEditing = signal(false);
|
|
protected address = signal<AddressResponse | null>(null);
|
|
|
|
@Input() set initialData(address: AddressResponse) {
|
|
if (address) {
|
|
this.addressForm.patchValue(address);
|
|
this.address.set(address);
|
|
this.isEditing.set(true);
|
|
}
|
|
}
|
|
|
|
submitForm() {
|
|
if (this.addressForm.invalid) {
|
|
this.addressForm.markAllAsTouched();
|
|
return;
|
|
}
|
|
|
|
const emittedData = this.addressForm.getRawValue() as AddressRequest;
|
|
|
|
if (this.isEditing()) {
|
|
const mergedData = { ...this.address(), ...emittedData };
|
|
this.updateAddress.emit(mergedData as unknown as AddressResponse);
|
|
} else {
|
|
this.submitAddress.emit(emittedData);
|
|
}
|
|
}
|
|
|
|
cancelEditing() {
|
|
this.addressForm.reset();
|
|
this.editingCanceled.emit();
|
|
}
|
|
}
|