68 lines
2 KiB
TypeScript
68 lines
2 KiB
TypeScript
import { HttpClient } from '@angular/common/http';
|
|
import { Component } from '@angular/core';
|
|
import { AbstractControl, FormArray, FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
|
|
import { Router, RouterLink } from '@angular/router';
|
|
import { Hotel } from '../HotelItem/hotel';
|
|
import { NgFor, NgIf } from '@angular/common';
|
|
|
|
@Component({
|
|
selector: 'app-new-hotel',
|
|
standalone: true,
|
|
imports: [ReactiveFormsModule, NgIf, NgFor, RouterLink],
|
|
templateUrl: './new-hotel.component.html',
|
|
styleUrl: './new-hotel.component.css'
|
|
})
|
|
export class NewHotelComponent {
|
|
public hotelForm!: FormGroup
|
|
public hotel!: Hotel
|
|
|
|
ngOnInit(): void {
|
|
const tags = [];
|
|
|
|
for (const tag of this.hotel?.tags ?? []) {
|
|
tags.push(new FormControl(tag, [Validators.required]));
|
|
}
|
|
|
|
|
|
this.hotelForm = new FormGroup({
|
|
name: new FormControl("", Validators.required),
|
|
description: new FormControl("", Validators.required),
|
|
price: new FormControl(0, Validators.required),
|
|
imageUrl: new FormControl("", Validators.required),
|
|
rating: new FormControl(0, Validators.required),
|
|
tags: new FormArray(tags)
|
|
})
|
|
}
|
|
|
|
getTags() {
|
|
return this.hotelForm.controls['tags'] as FormArray;
|
|
}
|
|
|
|
deleteTag(tagElement: AbstractControl) {
|
|
this.getTags().removeAt(this.getTags().controls.indexOf(tagElement));
|
|
}
|
|
|
|
|
|
addTag() {
|
|
this.getTags().push(new FormControl('', [Validators.required]));
|
|
}
|
|
|
|
constructor(public http: HttpClient, public router: Router) {
|
|
|
|
}
|
|
|
|
submit(): void {
|
|
console.log(this.hotelForm.value);
|
|
const hotel: Hotel = {
|
|
id: 0,
|
|
hotelName: this.hotelForm.get("name")?.value,
|
|
description: this.hotelForm.get("description")?.value,
|
|
price: this.hotelForm.get("price")?.value,
|
|
imageUrl: this.hotelForm.get("imageUrl")?.value,
|
|
rating: this.hotelForm.get("rating")?.value,
|
|
tags: this.hotelForm.get("tags")?.value
|
|
}
|
|
this.http.post("/api/hotels/", hotel).subscribe();
|
|
this.router.navigate(["/"]);
|
|
}
|
|
}
|