diff --git a/src/app/hotel-form/hotel-form.component.ts b/src/app/hotel-form/hotel-form.component.ts index 649dd1f..67d523c 100644 --- a/src/app/hotel-form/hotel-form.component.ts +++ b/src/app/hotel-form/hotel-form.component.ts @@ -36,9 +36,7 @@ export class HotelFormComponent { return this.validationErrorMessages[key] || `Unknown error: ${key}`; }).join(' '); - console.log(this.errorMsg); } - console.log(this.errorMsg); } updateErrorMessages(): void { @@ -53,8 +51,6 @@ export class HotelFormComponent { .join(' '); } }); - - console.log(this.errorMessages); } ngOnInit(): void { diff --git a/src/app/new-hotel/new-hotel.component.html b/src/app/new-hotel/new-hotel.component.html index 6979b52..382fdde 100644 --- a/src/app/new-hotel/new-hotel.component.html +++ b/src/app/new-hotel/new-hotel.component.html @@ -2,14 +2,19 @@
+
{{ errorMessages['name'] }}
+
{{ errorMessages['description'] }}
+
{{ errorMessages['imageUrl'] }}
- +
{{ errorMessages['price'] }}
+ +
{{ errorMessages['rating'] }}
@for (tag of getTags().controls; track null) { diff --git a/src/app/new-hotel/new-hotel.component.ts b/src/app/new-hotel/new-hotel.component.ts index 07ab317..a6755b7 100644 --- a/src/app/new-hotel/new-hotel.component.ts +++ b/src/app/new-hotel/new-hotel.component.ts @@ -15,6 +15,30 @@ import { NgFor, NgIf } from '@angular/common'; export class NewHotelComponent { public hotelForm!: FormGroup public hotel!: Hotel + errorMessages: Record = {}; + + private validationErrorMessages: Record = { + required: "This field is required", + minlength: "The value is too short", + maxlength: "The value is too long", + pattern: "The value format is incorrect" + }; + + updateErrorMessages(): void { + this.errorMessages = {}; + + Object.keys(this.hotelForm.controls).forEach(field => { + const control = this.hotelForm.get(field); + + if (control && control.errors && control.touched) { + this.errorMessages[field] = Object.keys(control.errors) + .map(errorKey => this.validationErrorMessages[errorKey] || `Unknown error: ${errorKey}`) + .join(' '); + } + }); + + console.log(this.errorMessages); + } ngOnInit(): void { const tags = []; @@ -32,6 +56,8 @@ export class NewHotelComponent { rating: new FormControl(0, Validators.required), tags: new FormArray(tags) }) + + this.hotelForm.valueChanges.subscribe(() => this.updateErrorMessages()); } getTags() {